Latest Laravel 8 Installation with REST API using Passport authentication

By | April 12, 2021

Hello Coders !! This article is about the Latest Laravel 8 Installation with REST API using Passport authentication.

Moreover, laravel REST API is used when we work with mobile application development or web application development.

In this article, we are going to use the passport package as an API authentication tool. So, no one can access the unauthorize API and we can restrict that only authenticated user will access this API.

Step 1: Install Latest Laravel 8

The first step we are going to install the latest laravel

The first and foremost thing we will do is open the terminal and run the below command for installation of the latest laravel 8.

Now you need to open the terminal and reach out to the working directory of your system.

Here is my case, my working directory is /Sites, So I am going to run the below command first.

cd Sites
Terminal command
Terminal command

Now we will run the below command to install Laravel 8

composer create-project --prefer-dist laravel/laravel laravel-api
Laravel 8 installation process
Laravel 8 installation process

After you run the above command the installation will be processed and the laravel fresh installation will be done on the laravel-api folder. So, we will reach out to that folder by running the below command.

cd laravel-api

Step 2: Database Setup

MySql database setup

Open up the “.env” from the root directory and add the database credential there.

Your .env file will look like this.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Here you need to add your database name, username, and password.

Step 3:  Run Laravel

Now you need to serve the Laravel using the below command

php artisan serve
Laravel 8 php artisan serve

Now, you can access the freshly installed Laravel 8 in your browser.

http://127.0.0.1:8000

Here default port will be 8000 for your current setup.

Laravel 8 Home page

Here you have completed the first part for the Latest Laravel 8 Installation with REST API using Passport authentication

Step 4: Passport package Installation

Now, we are going to install the passport package for authentication.

Run the below command in your terminal for installation of the passport authentication package. For that, you should be inside the project directory.

composer require laravel/passport
Laravel 8 passport installation
Laravel 8 passport installation

After the passport package installation successfully we need to migrate the table inside the database. For that run the below command in a terminal inside the project directory.

php artisan migrate

This command will migrate all the tables inside the database.

Laravel 8 Migration table
Laravel 8 Migration table

Now you need to run the below command for passport token keys generation for security.

php artisan passport:install

Step 5: Passport Package Configuration


Open app/Models/User.php file. And we will be going to add HasApiTokens in this model file.

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

Now, Open the “config/auth.php” file and add the below code to it.

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Authentication Defaults
    |--------------------------------------------------------------------------
    |
    | This option controls the default authentication "guard" and password
    | reset options for your application. You may change these defaults
    | as required, but they're a perfect start for most applications.
    |
    */

    'defaults' => [
        'guard' => 'web',
        'passwords' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | Supported: "session", "token"
    |
    */

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
        'api' => [
            'driver' => 'passport',
            'provider' => 'users',
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user's data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\Models\User::class,
        ],

        // 'users' => [
        //     'driver' => 'database',
        //     'table' => 'users',
        // ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    'passwords' => [
        'users' => [
            'provider' => 'users',
            'table' => 'password_resets',
            'expire' => 60,
            'throttle' => 60,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Password Confirmation Timeout
    |--------------------------------------------------------------------------
    |
    | Here you may define the amount of seconds before a password confirmation
    | times out and the user is prompted to re-enter their password via the
    | confirmation screen. By default, the timeout lasts for three hours.
    |
    */

    'password_timeout' => 10800,

];

Step 6: Create category table with model and controller file

Now, the next step is we will create the category table so we can create REST API for the category table. You can make your own tables for the API.

Run the below command in your terminal for creating a table.

php artisan make:migration create_categories_table

This command will create the migration file in your project Now you need to add a few attributes to it. And it will look like the below code.

Path: laravel-api/database/migrations/2021_04_09_113916_create_categories_table.php

<?php

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

class CreateCategoryTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('cat_name');
            $table->tinyInteger('cat_status');
            $table->timestamps();
        });
    }

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

The next step is now we need to migrate this table to the database using the below terminal command.

php artisan migrate

After creating the table we will create the model of this table. To do that run the below command in your terminal.

php artisan make:model Category

This will create the model file at app/Models/Category.php and after update the file it will look like this.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $fillable = [
        'cat_name', 'cat_status'
    ];
}

Now we will create these three controller files for Category using the below command.

php artisan make:controller API/CategoryController
php artisan make:controller API/RegisterController
php artisan make:controller API/BaseController

These three controller files will look like this after the update.

CategoryController.php

<?php
   
namespace App\Http\Controllers\API;
   
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\Category;
use Validator;
use App\Http\Resources\Category as CategoryResource;
   
class CategoryController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $Categorys = Category::all();
    
        return $this->sendResponse(CategoryResource::collection($Categorys), 'Categorys retrieved successfully.');
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'cat_name' => 'required',
            'cat_status' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $Category = Category::create($input);
   
        return $this->sendResponse(new CategoryResource($Category), 'Category created successfully.');
    } 
   
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $Category = Category::find($id);
  
        if (is_null($Category)) {
            return $this->sendError('Category not found.');
        }
   
        return $this->sendResponse(new CategoryResource($Category), 'Category retrieved successfully.');
    }
    
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Category $Category)
    {
        $input = $request->all();
   
        $validator = Validator::make($input, [
            'cat_name' => 'required',
            'cat_status' => 'required'
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $Category->cat_name = $input['cat_name'];
        $Category->cat_status = $input['cat_status'];
        $Category->save();
   
        return $this->sendResponse(new CategoryResource($Category), 'Category updated successfully.');
    }
   
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Category $Category)
    {
        $Category->delete();
   
        return $this->sendResponse([], 'Category deleted successfully.');
    }
}

RegisterController.php

<?php
   
namespace App\Http\Controllers\API;
   
use Illuminate\Http\Request;
use App\Http\Controllers\API\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
   
class RegisterController extends BaseController
{
    /**
     * Register api
     *
     * @return \Illuminate\Http\Response
     */
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->accessToken;
        $success['name'] =  $user->name;
   
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }
}

BaseController.php

<?php


namespace App\Http\Controllers\API;


use Illuminate\Http\Request;
use App\Http\Controllers\Controller as Controller;


class BaseController extends Controller
{
    /**
     * success response method.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendResponse($result, $message)
    {
    	$response = [
            'success' => true,
            'data'    => $result,
            'message' => $message,
        ];


        return response()->json($response, 200);
    }


    /**
     * return error response.
     *
     * @return \Illuminate\Http\Response
     */
    public function sendError($error, $errorMessages = [], $code = 404)
    {
    	$response = [
            'success' => false,
            'message' => $error,
        ];


        if(!empty($errorMessages)){
            $response['data'] = $errorMessages;
        }


        return response()->json($response, $code);
    }
}

Now, We need to write the routes of the API in route files which are located at “routes/api.php”

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\API\RegisterController;
use App\Http\Controllers\API\CategoryController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/


// Routes for Register and login
Route::post('register', [RegisterController::class, 'register']);
Route::post('login', [RegisterController::class, 'login']);
Route::post('product-add', [CategoryController::class, 'store']);


Route::middleware('auth:api')->group( function () {
    Route::resource('category', CategoryController::class);
});

// Route::middleware('auth:api')->get('/user', function (Request $request) {
//     return $request->user();
// });

Create Eloquent API Resources using the below command

php artisan make:resource Category

This will create the resource file at app/Http/Resources/Category.php 

After the update, it will look like this.

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Category extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
         return [
            'id' => $this->id,
            'cat_name' => $this->cat_name,
            'cat_status' => $this->cat_status,
            'created_at' => $this->created_at->format('d/m/Y'),
            'updated_at' => $this->updated_at->format('d/m/Y'),
        ];
    }
}

Above all, we came to a stage that all the required things have been done so not it’s too time to serve the laravel project using the below command.

php artisan serve

Now you can access your project using this URL: http://localhost:8000

Step 7: Postman API calls

Now we are all set up for testing API. Open Postman in your system to check API. You can download the postman and install it if you don’t have it.

Postman setup

postman setup
postman setup

Setup your Headers like this.

postman body
postman body

You can set the register parameter like this.

postman successful response
postman successful response

Your postman’s successful response will look like this.

Same for Login API

postman login API
postman login API

Product Add API in postman

postman product add
postman product add

We are done here, coders !! We are done with the Latest Laravel 8 Installation with REST API using Passport authentication token alongside the postman API demo.

For instance, if you want to check the Laravel upgrade article from 7 to 9 then check the Laravel Framework upgrade from older version 7.x to 8.x. Let us know about it in the comments !!

Here is the whole source code at GITHUB.

Leave a Reply

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