In this tutorial you will learn about the Laravel 9 User Registration Login Api with Passport Authentication and its application with practical example.
In this Laravel 9 User Registration Login Api with Passport Authentication Tutorial I will show you how to create user authentication(registration and login) REST API with passport authentication In laravel. In this tutorial you will learn to create authentication rest api with passport authentication In laravel 9 application. In this article I will share example to create rest api for user authentication using passport authentication in laravel 9. I will also show you how to install passport authentication package in laravel 9. After installing and configure passport authentication in laravel we will create simple user authentication rest api.
Laravel 9 User Authentication API
By user authentication means to validation and authentication valid application users. User authentication allows to register new user into application and to login existing application users. In this tutorial we will be creating user authentication api means we will be creating rest api for user registration, login and to get user info. We will be using passport authentication for creating rest api for user authentication in this example laravel 9 application.
Laravel 9 User Registration Login Api with Passport Authentication
In this step by step tutorial I will guide you through create a fully functional restful API with passport authentication in Laravel 9. Please follow the instruction given below:
- Install Laravel 9
- Set Up Database
- Install Passport Package
- Configure Passport Module
- Create Post Model & Run Migration
- Create a New Controller
- Define API Routes
- Test Laravel Passport API
Install Laravel 9
First of all we need to create a fresh laravel project, download and install Laravel using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Configure Database
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=here your database name here DB_USERNAME=here database username here DB_PASSWORD=here database password here |
Install Passport Package
In this step, we need to install Laravel Passport package via the composer dependency manager. Use the following command to install passport package.
1 |
composer require laravel/passport |
After successfully install laravel passport, register providers. Open config/app.php . Put the bellow code in it:
config/app.php
1 2 3 4 5 |
// config/app.php 'providers' =>[ Laravel\Passport\PassportServiceProvider::class, ], |
Now, it is mandatory to install passport using the command below. This command will generate encryption keys required to generate secret access tokens.
1 |
php artisan passport:install |
Passport Configuration
Open User.php model file and add ‘Laravel\Passport\HasApiTokens’ trait in it.
app/Models/User.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?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', ]; } |
go to app/Providers/AuthServiceProvider.php file and register the registerPolicies() method inside the boot() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?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(); } } |
config/auth.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php return [ ..... 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ], ..... ] |
Run Migration
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Create Passport Auth Controller
Now, lets create a controller named PassportAuthController using command given below –
1 |
php artisan make:controller Api\PassportAuthController |
Once the above command executed, it will create a controller file PassportAuthController.php in app/Http/Controllers/Api/ directory. Open the PassportAuthController.php file and put the following code in it.
app/Http/Controllers/Api/PassportAuthController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
<?php namespace App\Http\Controllers\API; use Illuminate\Http\Request; use App\Models\User; class AuthController extends Controller { /** * Registration Req */ public function register(Request $request) { $this->validate($request, [ 'name' => 'required|min:4', 'email' => 'required|email', 'password' => 'required|min:8', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password) ]); $token = $user->createToken('Laravel-9-Passport-Auth')->accessToken; return response()->json(['token' => $token], 200); } /** * Login Req */ public function login(Request $request) { $data = [ 'email' => $request->email, 'password' => $request->password ]; if (auth()->attempt($data)) { $token = auth()->user()->createToken('Laravel-9-Passport-Auth')->accessToken; return response()->json(['token' => $token], 200); } else { return response()->json(['error' => 'Unauthorised'], 401); } } public function userInfo() { $user = auth()->user(); return response()->json(['user' => $user], 200); } } |
Define API Routes
Now we will define authentication rest API routes. Go to the routes directory and open api.php. Then put the following routes into api.php file:
routes/api.php
1 2 3 4 5 6 7 8 |
use App\Http\Controllers\API\PassportAuthController; Route::post('register', [PassportAuthController::class, 'register']); Route::post('login', [PassportAuthController::class, 'login']); Route::middleware('auth:api')->group(function () { Route::get('get-user', [PassportAuthController::class, 'userInfo']); }); |
Start Development Server
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Laravel 9 User Registration API:
1 |
http://localhost:8000/api/register |
Laravel 9 User Login API:
1 |
http://localhost:8000/api/login |