RESTful API Development Laravel 6.x

In this tutorial, we will create a simple RESTFUL API using Laravel Version 6. I assume you already familiar with create a new Laravel project and connect to the database. Afterwards, follow these steps together :

Install Laravel Passport

Run migration

We will find additional tables on the database :

Laravel CRUD API

Run this command to get Laravel personal access client and laravel password grant client in oauth_clients table.

The next step is to add HasApiTokens to User.php model :

config/auth.php

Change the api driver from token (default) to passport :

AuthServiceProvider.php

At the boot() method, add Passport route:

This will add additional routes to our application. We will be able to see the routes by type this command to the terminal :

kernel.php

This line of code will make passport do the authorization under the hood, so we don’t need to put Authorization Bearer everytime to authenticate api requests.

Requesting a Passport Token

In this session we will see how to handle the access token.

Create route to get the token :

Modify LoginController.php and add the getToken method :

Don’t forget to use the following methods :

Modify your .env file and change the APP_URL to your url. For example, http://localhost:8000.

We got the client_id and client_secret from oauth_clients table that we have created previously.

Try the Endpoint using Postman

Install and open postman, then using POST method open the endpoint, add Accept – application/json to your header, and on the body, add the username and password :

Laravel CRUD Restful API

If everything goes well, you will get the access_token as the response. When we perform the request on the web, later we don’t need to copy and paste this access_token as we already put CreateFreshApiToken inside the kernel.php.

API Endpoint to GET All Records

Here I already have a post table :

Laravel CRUD API

Later we will put this information to postman.

Create PostController inside API folder :

Open routes/api.php

Api\PostController.php

The result can be seen in your browser :

Laravel CRUD Api

Eloquent API Resource

Before Laravel 5.5, we usually use Fractal as an transformation layer. However, since version 5.5, we can use eloquent api resource.

Create Resource from the terminal :

Post table related to user table through author_id column. Therefore, create the relation on Post.php and User.php :

Post.php

User.php

UserResource.php

PostResource.php

Modify PostController.php

The result can be seen on your browser with the better json structure.

Endpoint to POST New Record

api.php

Create route for apiResource :

To add some rule, let’s create a new request

PostStoreRequest.php

PostController.php

At the store method, add the following command to add the new post :

This will return the message and post in json format.

Open postman, POST the api url and put title, slug, and body in the body part :

Laravel CRUD Restful API

Update and Delete Record using PUT and DELETE

Create Policy

Before we update and delete the post, there is one middleware that we need to apply. We will create a policy so only the user that create the post is able to update and delete their own post. They will not be able to update or delete other people’s post.

Firstly, create a policy :

Modify the policy to include update and delete method :

App\Policies\PostPolicy.php

AuthServiceProvider.php

Kernel.php

Add the following lines if you find session error :

Next, open Api/PostController.php and modify update and destroy method :

Open Postman and run the PUT and DELETE method :

Laravel CRUD Api Restful

Laravel CRUD Api Restful Delete

Api Endpoint to GET Post Detail

In this section, we will create a response when there is post_detail table. Here is the table structure and content :

Laravel Restful API post detail

Create the PostDetail.php model with relation to Post model :

Subsequently, create a new route with no middleware so anyone will be able to see :

Create PostDetailResource :

Create PostDetailController inside Api folder :

-i means invoked.

Open Postman and send the request :

Laravel Restful API Post Detail

We can see that the post detail belongs to another post, and the post is created by user with id number 2.

 

 

 

5 thoughts on “RESTful API Development Laravel 6.x

  • I have an error when try to run this command:
    php artisan route:list --name=passport

    The erros is:

    Hendis-MacBook-Pro:laravel-api2 hendisantika$ php artisan route:list --name=passport

    Error

    Class 'App\Providers\Passport' not found

    at app/Providers/AuthServiceProvider.php:27
    23| */
    24| public function boot()
    25| {
    26| $this->registerPolicies();
    > 27| Passport::routes();
    28| }
    29| }
    30|

    +8 vendor frames
    9 [internal]:0
    Illuminate\Foundation\Application::Illuminate\Foundation\{closure}(Object(App\Providers\AuthServiceProvider))

    +5 vendor frames
    15 artisan:37
    Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))

    Any advices?
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.