Laravel 11 using Passport REST API Authentication Tutorial
Run the following composer command to install and create a new Laravel project:
composer create-project --prefer-dist laravel/laravel passport-auth-example
Step 2: Install Laravel Passport
Install passport auth to create rest API:
php artisan install:api --passport
Step 3 – Configure Passport
Edit your user.php model from app/models folder, and add the HasApiTokens trait:
<?php namespace App\Models; 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<int, string> */ protected $fillable = [ 'user_id', 'name', 'email', 'join_date', 'last_login', 'phone_number', 'status', 'role_name', 'avatar', 'position', 'department', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; /** * Boot method for model event hooks. */ protected static function boot() { parent::boot(); self::creating(function ($model) { $latestUser = self::orderBy('user_id', 'desc')->first(); $nextID = $latestUser ? intval(substr($latestUser->user_id, 3)) + 1 : 1; do { $model->user_id = 'KH_' . sprintf("%03d", $nextID++); } while (self::where('user_id', $model->user_id)->exists()); }); } }
Step 4 – Add User Table
Next, we need to create a migration for the products table using the Laravel artisan command. So first, execute the command below:
php artisan make:migration create_user_table
After this command, you will find one file in the following path: database/migrations. You must put the code below in your migration file to create the products table.
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { // Users Table Schema::create('users', function (Blueprint $table) { $table->id(); // Auto-increment primary key $table->string('user_id')->unique(); // Custom user ID, must be unique $table->string('name')->nullable(); $table->string('email')->unique(); // Email should be unique $table->date('date_of_birth')->nullable(); // Date type for date_of_birth $table->date('join_date')->nullable(); // Date type for join_date $table->string('phone_number')->nullable(); $table->string('status')->nullable()->index(); // Add index for frequently filtered columns $table->boolean('two_step')->default(false); // Use boolean for true/false values $table->timestamp('last_login')->nullable(); $table->string('role_name')->nullable()->index(); // Index for role_name $table->string('avatar')->nullable(); $table->string('position')->nullable(); $table->string('department')->nullable(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); // Non-nullable password $table->rememberToken(); $table->timestamps(); }); // Password Reset Tokens Table Schema::create('password_reset_tokens', function (Blueprint $table) { $table->string('email')->primary(); // Primary key $table->string('token'); // Reset token $table->timestamp('created_at')->nullable(); }); // Sessions Table Schema::create('sessions', function (Blueprint $table) { $table->string('id')->primary(); // Primary key $table->foreignId('user_id')->nullable()->constrained('users')->cascadeOnDelete(); // Foreign key $table->string('ip_address', 45)->nullable(); // IPv4/IPv6 compatible $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); // Indexed for performance }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('sessions'); Schema::dropIfExists('password_reset_tokens'); Schema::dropIfExists('users'); } };
Edit config/auth.php file and API driver:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
Step 5 – Set Up Database
Edit the .env file and configure database details in it:
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
Step 6 – Migrate Database:
Run the database migrations to create the necessary tables in your database:
php artisan migrate
Step 7: Install route api
You may install Laravel Sanctum via the install:api Artisan command:
php artisan install:api
Step 8 – Create API Routes
Next, define the routes for your API endpoints. Open your api.php file located at routes/api.php and define your routes:
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\API\AuthenticationController; Route::prefix('auth')->group(function () { // Public routes (no middleware) Route::controller(AuthenticationController::class)->group(function () { Route::post('register', 'register')->name('auth.register'); Route::post('login', 'login')->name('auth.login'); Route::post('logout', 'logOut')->name('auth.logout'); }); // Protected routes (requires authentication) Route::middleware('auth:api')->controller(AuthenticationController::class)->group(function () { Route::get('user', 'userInfo')->name('auth.user'); }); });
Step 9 – Create Controller and Method
Create a controller file by using the following command:
php artisan make:controller API/AuthenticationController
Now implement authentication methods into it to handle login, registration, and user detail functionality from the database:
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; use App\Models\User; use Carbon\Carbon; class AuthenticationController extends Controller { /** * Register a new account. */ public function register(Request $request) { $validatedData = $request->validate([ 'name' => 'required|min:4', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|min:8', ]); $user = User::create([ 'name' => $validatedData['name'], 'email' => $validatedData['email'], 'password' => Hash::make($validatedData['password']), 'join_date' => Carbon::now()->toDayDateTimeString(), ]); return response()->json([ 'response_code' => '200', 'status' => 'success', 'message' => 'Registration successful', 'data' => $user, ], 200); } /** * Handle login requests. */ public function login(Request $request) { $credentials = $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', ]); if (!Auth::attempt($credentials)) { return response()->json([ 'response_code' => '401', 'status' => 'error', 'message' => 'Invalid credentials', ], 401); } $user = Auth::user(); $accessToken = $user->createToken('authToken')->accessToken; return response()->json([ 'response_code' => '200', 'status' => 'success', 'message' => 'Login successful', 'data' => [ 'user' => $user, 'token' => $accessToken, ], ], 200); } /** * Retrieve paginated user information. */ public function userInfo() { try { $users = User::latest()->paginate(10); return response()->json([ 'response_code' => '200', 'status' => 'success', 'message' => 'User list retrieved successfully', 'data' => [ 'users' => $users->items(), 'pagination' => [ 'total' => $users->total(), 'per_page' => $users->perPage(), 'current_page' => $users->currentPage(), 'last_page' => $users->lastPage(), ], ], ], 200); } catch (\Exception $e) { Log::error($e); return response()->json([ 'response_code' => '500', 'status' => 'error', 'message' => 'Failed to retrieve user list', ], 500); } } }
Step 10 – Personal
To create a personal access client in Laravel, you can use the following Artisan command:
php artisan passport:client --personal
Step 11 – Testing
Run the artisan serve command to start the application server:
php artisan serve
- Open Postman.
- Set the request type to POST.
- Enter http://yourdomain.com/api/register in the address bar (replace yourdomain.com with your domain).
- Go to the Body tab.
- Choose x-www-form-urlencoded and select JSON.
- Enter the user registration data in JSON format, including name, email, and password.
- Click on the Send button to register the user.
- Set the request type to POST.
- Enter the URL of your Laravel application followed by /api/login (e.g., http://yourdomain.com/api/login).
- Go to the Body tab.
- Select x-www-form-urlencoded and set the format to JSON.
- Enter the user’s credentials (email and password) in JSON format.
- Click on the Send button to log in. You will receive a token in the response if the login is successful.
- Set the request type to GET.
- Enter the URL of your Laravel application followed by /api/get-user (e.g., http://yourdomain.com/api/get-user).
- Go to the Headers tab.
- Add a new header with the key Authorization and the value, where <token> the token is obtained during the login process.
- Click on the Send button to get the user information.