Create REST API with Passport authentication Laravel 6 Tutorial

In this laravel 6 rest authentication api example, we are going to show you, how to create restfull apis in laravel 6 using passport authentication. Step by Step guide to build rest apis in laravel application using passport authentication in laravel applications. Laravel passport authenticate users and do not maintain session.

Today, first of all we will install laravel new setup and second thing, install laravel passport package for creating a rest full api and using the api we will authentication users in laravel based app.

Laravel Passport Tutorial


  • Download Fresh Laravel
  • Install Passport Packages in Laravel
  • Run Migration and Install Laravel Passport
  • Passport Configuration
  • Create Api Route
  • Create Controller & Methods
  • Conclusion

Download Fresh Laravel

Download Laravel fresh setup using below command, Open command prompt and Type the below command:

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

Install Passport Package In Laravel

In this step run the below command and install passport package :

composer require laravel/passport

After successfully install laravel passport, register providers. Open config/app.php . and put the bellow code :

  // config/app.php

'providers' =>[

Before you run migration command , go to the app/providers/AppServiceProvider.php and put the two line of code inside a boot method :

 Use Schema; 
public function boot() {

Run Migration and Install Laravel Passport

We need to do migration using bellow command. This command create tables in database :

php artisan migrate

We need to install laravel generate passport encrption keys. This command will create the encryption keys needed to generate secure access tokens . like secret key and secret id.

php artisan passport:install

Laravel Passport Configuration

Configuration some file . Next open App/User.php file and put the below code on App/User.php File

use Laravel\Passport\HasApiTokens;

use HasApiTokens,
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',

Next Register passport routes in App/Providers/AuthServiceProvider.php, Go to App/Providers/AuthServiceProvider.php and put this => Register Passport::routes(); inside of boot method :

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() 


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

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

Create API Route

In this step,we will create api routes, go to api.php inside route folder and create below routes here :

	Route::post('login', 'Api\[email protected]');
	Route::post('register', 'Api\[email protected]');
	Route::group(['middleware' => 'auth:api'], function() {
		Route::get('getUser', 'Api\[email protected]');

Create Controller

Now will create a controller name AuthController. Use the below command and create controller :

 php artisan make:controller Api\AuthController

After that we will create some methods in authController :

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 AuthController extends Controller 
 public $successStatus = 200;
 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('AppName')->accessToken;
 return response()->json(['success'=>$success], $this->successStatus); 
public function login(){ 
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ 
   $user = Auth::user(); 
   $success['token'] =  $user->createToken('AppName')-> accessToken; 
    return response()->json(['success' => $success], $this-> successStatus); 
  } else{ 
   return response()->json(['error'=>'Unauthorised'], 401); 
public function getUser() {
 $user = Auth::user();
 return response()->json(['success' => $user], $this->successStatus); 
 Lets got terminal & run the command :

 php artisan serve

Now Test Rest Api in Postman

Laravel Register Api :
laravel register api
laravel register api
Login Api :
laravel passport login api
laravel passport login api

Next Step , we will call getUser api, In this api you have to set two header followning :

Call login or register apis put $accessToken.

‘headers’ => [
‘Accept’ => ‘application/json’,
‘Authorization’ => ‘Bearer ‘.$accessToken,


Pass header in login / register rest api. it is neccessary to passport authentication in laravel app


Laravel passport – We have successfully install laravel passport package and also configuration passport package in laravel application. Using the laravel passport package we have successfully create rest authentication login api, register api and get user info api.

If you have any questions or thoughts to share, use the comment form below to reach us.


  1. Zahid Kazmi said:

    Route::post(‘login’, ‘Api\[email protected]’);
    Route::post(‘register’, ‘Api\[email protected]’);
    Route::group([‘middleware’ => ‘auth:api’], function(){
    Route::post(‘getUser’, ‘Api\[email protected]’);

    D:\xampp\htdocs\amsapi> php artisan serve

    ErrorException : Non-static method Illuminate\Routing\Route::prefix() should not be called statically

    at D:\xampp\htdocs\amsapi\routes\api.php:17
    13| | is assigned the “api” middleware group. Enjoy building your API!
    14| |
    15| */
    > 17| Route::prefix(‘v1’)->group(function(){
    18| Route::post(‘login’, ‘Api\[email protected]’);
    19| Route::post(‘register’, ‘Api\[email protected]’);
    20| Route::group([‘middleware’ => ‘auth:api’], function(){
    21| Route::post(‘getUser’, ‘Api\[email protected]’);

    Exception trace:

    1 Illuminate\Foundation\Bootstrap\HandleExceptions::handleError(“Non-static method Illuminate\Routing\Route::prefix() should not be called statically”, “D:\xampp\htdocs\amsapi\routes\api.php”, [“D:\xampp\htdocs\amsapi\routes/api.php”, Object(Illuminate\Routing\Router)])

    2 require(“D:\xampp\htdocs\amsapi\routes\api.php”)

    Please use the argument -v to see more details.
    Then i write following code for routes
    Route::group([‘prefix’ => ‘v1’], function () {
    Route::post(‘login’,’Api\[email protected]’);
    Route::post(‘register’,’Api\[email protected]’);
    Route::group([‘middleware’ => ‘auth:api’], function(){
    Route::post(‘getUser’,’Api\[email protected]’);
    then i get following exceptions:
    D:\xampp\htdocs\amsapi> php artisan serve

    BadMethodCallException : Method Illuminate\Routing\Route::group does not exist.

    at D:\xampp\htdocs\amsapi\vendor\laravel\framework\src\Illuminate\Support\Traits\Macroable.php:77
    73| */
    74| public static function __callStatic($method, $parameters)
    75| {
    76| if (! static::hasMacro($method)) {
    > 77| throw new BadMethodCallException(sprintf(
    78| ‘Method %s::%s does not exist.’, static::class, $method
    79| ));
    80| }

    Exception trace:

    1 Illuminate\Routing\Route::__callStatic(“group”)

    2 require(“D:\xampp\htdocs\amsapi\routes\api.php”)

    Please use the argument -v to see more details.

    kindly help me out what is going wrong.

    October 30, 2019
    • w3path said:

      Please share the Laravel version you are using

      If possible upload your code on github and share public URL

      November 3, 2019
  2. Luis Colmenares said:

    Thank you for sharing this!.

    The only issue I found was on one of the API routes.

    getUser is set as a POST request, and it should be a GET request.

    Route::post(‘login’, ‘Api\[email protected]’);
    Route::post(‘register’, ‘Api\Aut[email protected]’);
    Route::group([‘middleware’ => ‘auth:api’], function(){
    Route::get(‘getUser’, ‘Api\[email protected]’);

    November 19, 2019
  3. andry said:

    ive got issue, when i tried to run on my hosting server,
    it give me response like this:
    “message”: “Unauthenticated.”
    only when i tried to access all route inside group([‘middleware’ => ‘auth:api’]).

    November 27, 2019

Leave a Reply

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