Create Laravel 8 RESTful APIs Using Passport Authentication

Create Laravel 8 RESTful APIs Using Passport Authentication

In this Laravel 8 tutorial, you will be learning to create a Laravel 8 REST API using Laravel passport authentication. You can create Laravel 8 REST API for global and specifically for any website or particular request. This kind of API requests will manage by a token. This token provides the privilege to access the response from the API. Laravel 8 passport authentication provides an authentication token for the API calls. When you will pass this auth token in the header as a bearer then you will have the access to the API call.

Displaying out JSON data only is not such an API. An API contains the data that synchronizes between the two applications. It connects two applications through an end-point. Basically, it works as an intermediary between the two applications. Every API request will have a response. So, in the overall process the API talks to another application to have the request and the response. You can create Laravel 8 REST API for global and specifically for any website or particular request. This kind of API requests will manage by a token. This token provides the privilege to access the response from the API. Laravel 8 passport authentication provides an authentication token for the API calls. When you will pass this auth token in the header as a bearer then you will have the access to the API call.

Otherwise, you won’t make a call to the API. Laravel 8 passport auth grants a secure and authenticated call for the APIs request. Today, in this Laravel 8 post, you will be learning to create a Laravel 8 REST API using Laravel passport authentication.

Contents

  • 1 Overview of this Application
  • 2 Prerequisites
  • 3 Create Project For Laravel 8 REST API with Passport
  • 4 Establish Database Connection For Passport Auth
  • 5 Install Passport Package in Laravel 8
  • 6 Create Models and Migrations For Laravel 8 REST API
  • 7 Add Fillable Data (Mass Assignment) For Models
  • 8 Add Auth Guard in Auth Service Provider
  • 9 Install Passport Auth Key
  • 10 Create Controllers For Laravel 8 Passport Authentication
  • 11 Add Routes of UserController
  • 11.1 Register User End Point
  • 11.2 User Login End Point
  • 11.3 User Detail End Point with Auth Token
  • 12 PostController Functionalities
  • 13 Add Routes for PostController
  • 13.1 POST Request For Creating Post
  • 13.2 GET Request For Fetching Posts
  • 13.3 GET Request For Post Detail
  • 13.4 PUT Request to Update Post
  • 13.5 DELETE Request to Delete a Post
  • 14 Conclusion

Overview of this Application

In this project, we will gonna create the RESTful APIs for the blog application. The basic blog application will have the user and post modules.

In the User module, I will create the following APIs –

  • Register
  • Login
  • Profile

In the Post module, the user can create the posts. But for creating and managing the posts, the user will require the login and the authentication token. This authentication token will be generated by the Passport auth. That means the post created by the user would be related to the same user only. Similarly, the logged user can edit, update, and delete only that post which is created by him/her. The post module will contain the following APIs –

  • Create post
  • Update post
  • Post detail
  • Delete post

Prerequisites

Before creating a RESTful API in Laravel 8, you must ensure that your system is ready with the following configurations.

  • PHP >= 7.3
  • MySQL (version > 5)
  • Apache/Nginx Server
  • VS Code Editor
  • Composer
  • Postman

Let’s create a new setup for the Laravel 8 REST API.

Create Project For Laravel 8 REST API with Passport

Create a new project setup in Laravel 8 using the composer.

create-project-for-rest-api
composer create-project --prefer-dist laravel/laravel rest-api-passport

Here, the project installation has started. It will take a couple of minutes to install the Laravel 8 files in the project directory.

Laravel 8 REST API passport authenticationCreate Project For Laravel 8 Passport authentication

After finishing the project setup, establish the database connection. Hence, create a database and connect it to the Laravel 8 application.

Establish Database Connection For Passport Auth

For the database, I am using the MySQL. Here, I have created a new database.

create-database
CREATE DATABASE laravel8_rest_api

After creating the database, you will require to have a connection with the project. Therefore, navigate the .env file of the project and replace the database credentials as showing below.

.env file - database-configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel8_rest_api
DB_USERNAME=root
DB_PASSWORD=root

I have connected the database with this project. Now, our application is ready to co-ordinate with the database. In the next step, we will be installing the package for the Laravel passport.

Install Passport Package in Laravel 8

For using the auth token in the RESTful API, firstly, we will have to install the Laravel 8 passport authentication package. So, let’s install it inside the project.

install-passport-package
composer require laravel/passport

Here, the passport package installation has been started.

Install Passport Package in Laravel 8

Install Passport Package in Laravel 8

After the installation of the passport package, we will create the models and migrations.

Create Models and Migrations For Laravel 8 REST API

Here, we have the default model and a migration for the User. Hence, we will require to create a model and migration for the post. So, open the terminal and create it.

create-post-model-and-migration
php artisan make:model Post --migration

The above command generated two files. One is model and another is the migration.

Create Model and Migration for Post

Create Model and Migration for Post

Now, we will have to specify the fields in both migration files. Currently, we have the users table and posts table migration. So, let’s do it one by one.

timestamp_create_users_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->string('phone')->nullable();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

For the post table migration, here are the specified fields.

timestamp_create_posts_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->bigInteger('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Here, we go with the mass assignment of the models.

laravel api php web-development developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...