Laravel 6 REST API with Passport Tutorial

  • 27-03-2022
  • 2486
  • Laravel 6
  • Haresh Chauhan

Watch Youtube Video (HINDI) :

Laravel 6 REST API with Passport is simply called API today IT world also known as a Web service. Web services (API) very important if you are creating web and mobile app development. If you develop a mobile app then you need to create API for your mobile application developer. As we know that laravel is the most popular framework because of the easy way of creating API. If you are a don't know what API and web services then you are the right place. In this example, I will show you how to create simple API and Authentication and get details of the Authenticated user. Before we start this example let us know what is the passport.

Laravel 6 REST API with Passport Tutorial

What is Passport?

APIs typically use tokens to authenticate users and do not maintain the state of the session between requests. Laravel 6 makes API authentication a platform using Laravel Passport, which provides a full OAuth2 server implement for your Laravel 6 application development in a few seconds.

Here, We must need to follow a few steps to get following web services (API)

1) Register API

2) Login API

3) Details API

Step 1: Install Laravel Application

In the first step we require to get fresh Laravel application using below command. So, Now open your terminal OR command prompt and run below command.

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install Laravel/Passport Package

We need to install the Laravel passport package after running the Laravel Fresh application.

composer require laravel/passport

After successfully install package.

Here, open config/app.php file and add service provider.

config/app.php

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

Step 3: Run Migration

In this step we require to run the migration command, after run migration command you will get few new tables in your database. So, let's follow below command.

php artisan migrate

Now we move on the install passport using the command, it will create a token key for security purposes. So let's run below command on your terminal.

php artisan passport:install

Step 4: Laravel Passport Configuration

Now, In this step we require to the change in three files. So, we have to do the configure on model, service provider and auth config file.

Here, You have to just follow change on that files.

In Model, Add HasApiTokens class of Passport,

In AuthServiceProvider Add “Passport::routes()”,

In auth.php, Add API auth configuration.

app/User.php

<?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',
    ];
}

app/Providers/AuthServiceProvider.php

<?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(); 
    } 
}

config/auth.php

<?php
return [
'guards' => [ 
    'web' => [ 
        'driver' => 'session', 
        'provider' => 'users', 
    ], 
    'api' => [ 
        'driver' => 'passport',  
        'provider' => 'users', 
    ], 
],

Step 5: Create API Routes

In the 5th step we require to create routes on the Laravel provides api.php file. Here, we create three routes.

So, let's add the new routes on that file.

routes/api.php

<?php
/*
|--------------------------------------------------------------------------
| 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!
|
*/
    Route::post('register', 'API\UserController@register');
    Route::post('login', 'API\UserController@login');

    Route::group(['middleware' => 'auth:api'], function(){
    Route::post('details', 'API\UserController@details');

});

Step 6 : Create the UserController

In the last step we have to create a User Controller and three API method, So we have to create first API directory on controller folder. So let's run bellow command.

php artisan make:controller API\UserController

After created controller put below UserController code.

app/Http/Controllers/API/UserController.php

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class UserController extends Controller 
{
    public $successStatus = 200;

    /** 
     * 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 response()->json(['error'=>$validator->errors()], 401);            
        }
            $input = $request->all(); 
            $input['password'] = bcrypt($input['password']); 
            $user = User::create($input); 
            $success['token'] =  $user->createToken('MyApp')->accessToken; 
            $success['name'] =  $user->name;
            return response()->json(['success'=>$success], $this->successStatus); 
    }

     /** 
     * login api 
     * 
     * @return \Illuminate\Http\Response 
     */ 

    public function login(){ 

        if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 

            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->accessToken; 
            return response()->json(['success' => $success], $this->successStatus); 
        } 
        else{ 
            return response()->json(['error'=>'Unauthorised'], 401); 
        } 
    }


    /** 
     * details api 
     * 
     * @return \Illuminate\Http\Response 
     */ 

    public function details() 
    { 
        $user = Auth::user(); 
        return response()->json(['success' => $user], $this->successStatus); 
    } 
}

Now we are ready to run this example ,So let's run below command.

php artisan serve

1) Register API

Here we are check in the REST API Response tools. Postman is the best REST API Response tools. You can get postman from this link Download.

Here, we check validation postman

Register Validation

Laravel REST API with passport - register validation Laravel REST API with passport - register

2) Login API

Laravel REST API with passport - Login

3) Details API

Laravel REST API with passport - Details

You can also download from github Laravel 6 REST API with Passport.

I hope it can help you.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :