- What is Laravel?
- Upgrade Laravel To 8.X
- Laravel-Media-Library
- Role Management
- Newsletter Package
- Form-Package
- Laravel Vs WordPress CMS
- New Laravel 6.X
- How To Make API In Laravel
- Laravel RSS/XML Feed
- How To Make Theme In Laravel?
- Laravel Project Testing Using PHPunit
- Laravel Package
- Make Contact Form In Laravel
- Laravel Homestead
- Laravel Cron Job
- What is Composer
- How to create an Admin-Panel in Laravel
- Admin Panel in Laravel
- Installation of Laravel in Windows
- Laravel Development
- Benefits of Laravel
- Laravel Notification
- How to make a Blog in Laravel
- Laravel Authentication
In this article, we’ll discuss how to make an API in Laravel. Before building an API, you’ll need to have RESTful endpoints, authentication and JSON responses. So, Laravel offer all of this out of the box. So, in this article, we will go through the steps to make RESTful API in Laravel.
Before going to the steps, we’ll get some overview about RESTful and Laravel Passport package.
RESTful action:
REST is stands for the Representational State Transfer which is an architectural style for network communication between applications and relies on the stateless protocol (Http). REST uses the methods such as GET, PUT, POST and DELETE.
Laravel Passport:
For API authentication we’ll use the Laravel Passport package. Laravel already makes it easy to perform authentication via traditional login forms, but in case of APIs, APIs uses the tokens to authenticate users and do not maintain session state between requests. Laravel makes API authentication a breeze using Laravel Passport, which provides the full OAuth2 server implementation for you Laravel application.
How to make an API in Laravel?
In this article we’ll make product reviews API. Users will add, update, delete the products and also view a list of products and review a product.
Note: Code for this API is available on GitHub: https://github.com/digitalcrm/LaraveAPI.git
Steps for make an API:
1. Install Laravel app:
Run the composer command: “composer create-project –prefer-dist laravel/laravel ProjectName”.
2. Create Database:
2.1. Connect Database with your Laravel project. Open database server and create new database
2.2. Connect with your project, go to “.env” file and change the DB_CONNECTION, Database, User_name and password. In phpMyAdmin the default value of user_name is root and password is null(empty):
3. Laravel Passport installation:
3.1. Run the command “composer require laravel/passport”
3.2. After this composer command, run the migrate command: “php artisan migrate”
3.3. Now, Install the passport using “php artisan passport:install” command.
Setup the passport installation:
After running the installation command, add the “Laravel\Passport\HasApiTokens” to your “App\User model”.
Next, you should call the “Passport::routes” method within the boot method of your AuthServiceProvider this file is located on “app/Provider/AuthServiceProvider” directory. And don’t forget to add the class of passport.
Open your config/auth.php configuration file and set the driver option of the api authentication guard to “passport”. This will instruct your application to use Passport’s TokenGuard when authentication incoming API requests.
How to Get Token in Passport:
After completing the all steps, now open postman and add few line in Body area such as grant_type, client_id, client_secret, username and password:
Client_secret will be obtaining from the database “oauth_clients” which is created by the passport automatically after install command.
For getting username and password, run the auth command: “php artisan make:auth”.
You will get the authentication in your project. Navigate “localhost:8000/user” in your browser. After this register the user as:
Next, after all done send the request, you’ll get the token.
After getting token, copy this token and make it on environment for easily accessing the data in API.
4. Creating Model:
4.1. Setup Migration Table:
Next, create the model for Product and Review. For Product run the command:
“php artisan make:model Model/Product –a”
For Review model, run the command: “php artisan make:model Model/Review –a”
Where “–a” will create the Controller, Model, Factories and Migration files for your application. After running this command, this will create files at your different directories.
Under “app/” directory, Controller located at “app/Http/Controller” directory and Model located at “app/Model” directory.
Migration and Factories will be located at under “database/”directory:
Next after creating models, add some line of code for creating table in database: For Products, open “database/migrations/create_products_table.php” file and add some line of code:
Open “database/migrations/create_reviews_table.php” file and add line of code for review table:
Next Run the migrate command; this command will creates the table in database.
4.2. Use Faker Table:
Open “database/factories/ProductFactory.php” file and add line of code for creating fake Product table:
Open “database/factories/ReviewFactory.php” file and add line of code for creating fake Review table:
After factories, open “database/seeds/DatabaseSeeder.php” file and add line of code for factory data.
Next, open terminal and enter command “php artisan db:seed”. This command will automatically add fake data into your database table.
4.3. Define relationship between models:
Product Model: open “app/Model/Product.php” file and add the relationship between User and Product.
Review Model: open “app/Model/Review.php” file and define relationship for reviews.
5. Defining the Controller for API:
5.1. Open “app/Http/Controller/ProductController.php” file and add the method for fetching the data, store data, update data and delete the data.
Fetching data add code in index() method:
Store the data in store() method:
Update the data in update() method:
Finally, deleting the data in destroy() method:
5.2. Open “app/Http/Controller/ReviewController.php” file and add the method for fetching the data, store data, update data and delete the data.
Fetching data add code in index() method:
Store the data in store() method:
Update the data in update() method:
Finally, deleting the data in destroy() method:
6. Creating Requests: For Product And Review
Creating the request for product, enter the command “php artisan make:request ProductRequest”
Adding code for Product request:
Creating the request for product, enter the command “php artisan make:request ReviewRequest”
Adding code for Review request:
7. Creating Resources:
Next, we have to define the resources for transforming the model and model collection into JSON. Basically when building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application’s users.
Command for creating the resources: “php artisan make:resource ResourceName”.
Creating Resources for Product: in this application we have created the ProductCollection and ProductResource.
Create ProductResource:
Create ProductCollection:
Resource ProductCollection and ProductResource located at “app/Http/Resources/Product” directory.
Next, open the ProuductResource.php file and add line of code:
Create ReviewResource: this file located at “app/Http/Resources/ReviewResource.php” directory.
Next, add line of code under ReviewResource file:
8. Routes:
Creating the routes for API, open the “routes/api.php” file and create route for products and reviews.
Run the command “php artisan route:list” for route the api for products and reviews.
9. Navigates Routes.
Open the postman (Postman is a collaboration platform for API development) and run the URL:
GET Product: http://localhost:8000/api/products:
PUT Product: http://localhost:8000/api/products/51
Delete Product: http://localhost:8000/api/products/51
Review Product: http://localhost:8000/api/products/4