Step 1. Install Laravel
If you have an existing Laravel running project, then you can skip this step. Otherwise, we require to get fresh Laravel application using below command, So open your terminal or command prompt and run command below:
composer create-project --prefer-dist laravel/laravel project_name
Step 2. Install Laravel Passport Package
To get started, install Passport via the Composer package manager:
composer require laravel/passport
Step 3. Run Migration
Firstly, .env
file:
DB_DATABASE=DATABASE NAMEDB_USERNAME=USERNAMEDB_PASSWORD=PASSWORD
Then do the migrations, Passport migrations will create the tables for your application in
php artisan migrate
Step 4. Generate keys
This command will create the encryption keys needed to generate secure access tokens. In addition, the command will create “personal access” and “password grant” clients which will be used to generate access tokens:
php artisan passport:install
Step 5. Passport Config
Add the Laravel\Passport\HasApiTokens
trait to your App\User
model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user’s token and scopes and HasApiTokens
in User
class :
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
}
Next, you should call the Passport::routes
method within the boot
method of your App/Providers/AuthServiceProvider
. This method will register the routes necessary to issue access tokens and revoke access tokens, clients, and personal access tokens. And Add this trait also use Laravel\Passport\Passport;
<?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
{
protected $policies = [
'App\Model' => 'App\Policies\ModelPolicy',
];
public function boot()
{
$this->registerPolicies();
Passport::routes();
}
}
Finally, in your config/auth.php
configuration file, you should set the driver
option of the api
authentication guard to passport
. This will instruct your application to use Passport’s TokenGuard
when authenticating incoming API requests:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
NOTE – In these first five steps, Installation of passport on any Laravel project has been done