LARAVEL Tutorial


Laravel 6 Create/Build REST APIs With Passport Auth Tutorial


Create or build rest APIs in laravel web application with passport auth. Here you will learn how to create or build rest APIs in laravel web applications. And also you will learn how to install a passport auth package and configure this package in your laravel web applications.

This tutorial has the purpose to explain to you how to easily install, configure and passport the auth package and create restful APIs in your laravel web applications.

Laravel Build REST Apis with Passport Auth Example Tutorial

  • Install Laravel Application
  • Configure Database Detail
  • Run Migration
  • Install Passport Auth & Configure
  • Create Routes
  • Generate Controller By Artisan
  • Start Development Server

Install Laravel Application

First Step, you need to download or install laravel web application new setup on your local machine. you can use the following command to download or install laravel application new setup:

composer create-project laravel/laravel laravel-rest-apis –-prefer-dist

If you want to install a specific version of laravel, you can follow the following tutorial

https://w3alert.com/laravel-tutorial/laravel-install-on-windows-ubuntu-with-composer

Configure Database Detail

After that, you will set up the database credentials in .env file. So open your .env file and update database credentials following:

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

Run Migration

Before you will run php artisan migrate command. Go to app/providers/AppServiceProvider.php and update the below code :

..
use Illuminate\Support\Facades\Schema;
 
....
function boot()
{
    Schema::defaultStringLength(191);
}
... 

Next, go to command prompt and run the following command:

php artisan migrate

OR

php artisan migrate:fresh

This php artisan migrate command creates a table in your database.

Install Passport Auth & Configure

Here, you will use the following command to install passport package in your laravel web applications

composer require laravel/passport

After successfully install a laravel passport, you can register providers. So go to config/app.php update the following codes:

// config/app.php

'providers' =>[
  Laravel\Passport\PassportServiceProvider::class,
 ],

Install Passport Auth

Here you will need to install and generate passport encryption keys. The following command generate secret key and secret id.

php artisan passport:install

Laravel Passport Configuration

Here you need to register passport routes in App/Providers/AuthServiceProvider.php. So Go to App/Providers/AuthServiceProvider.php and update  Passport::routes(); inside of boot method :

<?php
namespace App\Providers;
use Laravel\Passport\Passport; 
use Illuminate\Support\Facades\Gate; 
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider 
{ 
    /** 
     * The policy mappings for the application. 
     * 
     * @var array 
     */
    protected $policies = [ 
        'App\Model' => 'App\Policies\ModelPolicy', 
    ];
/** 
     * Register any authentication / authorization services. 
     * 
     * @return void 
     */
    public function boot() 
    { 
        $this->registerPolicies(); 
        Passport::routes(); 
    } 
}

Next Open config/auth.php and Change the API driver to the session to passport. Put this code ‘driver’ => ‘passport’, in API :

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

After that, open App/User.php file and update the following line use Laravel\Passport\HasApiTokens;, and use HasApiTokens, Notifiable; into your User.php file. You can following below:

<?php
namespace App;
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
 
class User extends Authenticatable
use HasApiTokens, 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',
];
}

Create Routes

Next step, go to routes/web.php file and update the following routes into your file:

Route::prefix('v1')->group(function(){

 Route::post('login', 'API\AuthController@login');

 Route::post('register', 'API\AuthController@register');

 Route::group(['middleware' => 'auth:api'], function(){

   Route::post('fetchUser', 'API\AuthController@loggedUser');

 });

});

Generate Controller By Artisan

Now, you need to generate or create a controller file using php artisan command, so use the php artisan make:controller command and generate/create a new controller file:

php artisan make:controller API/AuthController

In this controller, we will make 3 methods. The first method name is registration(), the second method name is login() and the third method name is loggedUser()

After that, go to App/Http/Controllers/ directory and find the created AuthController.php controller file and update the following code into your file:

<?php 
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use Illuminate\Support\Facades\Auth; 
use Validator;
use App\User; 

class AuthController extends Controller 
{
 public $statusCode = 200;
  
 public function register(Request $request) 
 {  

    request()->validate([
    'name' => 'required',
    'email' => 'required|email',
    'password' => 'required',  
    'c_password' => 'required|same:password', 
    ]);

    $input = $request->all();  

    $input['password'] = bcrypt($input['password']);

    $user = User::create($input); 

    $success['token'] =  $user->createToken('AppName')->accessToken;

    return response()->json(['success'=>$success], $this->statusCode); 
}
  
   
public function login(Request $request)
{ 

    request()->validate([
    'email' => 'required|email',
    'password' => 'required',  
    ]);

    if(Auth::attempt(['email' => $request->email, 'password' => $request->password]))
    { 
       $user = Auth::user(); 
       $success['token'] =  $user->createToken('AppName')->accessToken; 
       return response()->json(['success' => $success], $this->statusCode); 
    } 
    else
    { 
      return response()->json(['error'=>'Unauthorised'], 401); 
    } 
}
  
  
public function loggedUser() 
{
  $user = Auth::user();
  return response()->json(['success' => $user], $this->statusCode); 
}

} 

Start development server

You can use the following command artisan command to start the development server:

php artisan serve

The final step, go to your postman call APIs with required parameters:

http://localhost:8000/login

OR

http://localhost/laravel-rest-apis/public/login