Laravel 10 REST API With Passport Authentication

Laravel 10 REST API With Passport Authentication

Laravel 10 REST API with Passport Authentication

In this guide, we’ll walk you through building a REST API in Laravel 10 with Passport authentication. You’ll learn how to set up Laravel Passport, create and authenticate users, and build secure API endpoints using standard CRUD operations.

Laravel Passport makes it easy to issue OAuth2 access tokens, perfect for mobile or SPA authentication.

Features Covered

  • Laravel 10 REST API setup

  • Authentication using Laravel Passport

  • User registration and login

  • Token generation and secure endpoints

  • Get the user list with pagination

Step 1: Install Laravel 10

Install Laravel using Composer:

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

Step 2: Install Laravel Passport

Install the Passport package:

composer require laravel/passport

Run the migrations and install Passport:

php artisan migrate php artisan passport:install

Step 3: Configure Auth Guards

Open config/auth.php and configure the API guard to use Passport:

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

Step 4: Create the User Table

Create the migration:

php artisan make:migration create_users_table

Inside the migration file, define the schema:

Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('user_id')->nullable(); $table->string('name')->nullable(); $table->string('email')->unique(); $table->string('date_of_birth')->nullable(); $table->string('join_date')->nullable(); $table->string('phone_number')->nullable(); $table->string('status')->nullable(); $table->string('two_step')->nullable(); $table->string('last_login')->nullable(); $table->string('role_name')->nullable(); $table->string('avatar')->nullable(); $table->string('position')->nullable(); $table->string('department')->nullable(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); });

Run the migration:

php artisan migrate

Step 5: Update User Model

In app/Models/User.php, add the HasApiTokens trait:

use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; protected $fillable = [ 'user_id', 'name', 'email', 'join_date', 'last_login', 'phone_number', 'status', 'role_name', 'avatar', 'position', 'department', 'password' ]; protected static function boot() { parent::boot(); self::creating(function ($model) { $getUser = self::orderBy('user_id', 'desc')->first(); $nextID = $getUser ? intval(substr($getUser->user_id, 3)) + 1 : 1; $model->user_id = 'KH_' . sprintf("%03s", $nextID); }); } }

Step 6: Create API Routes

Edit routes/api.php:

use App\Http\Controllers\Auth\LoginController; use App\Http\Controllers\Auth\RegisterController; use App\Http\Controllers\UserManagementController; Route::prefix('auth')->group(function () { Route::post('login/push', [LoginController::class, 'authenticate']); Route::post('register/save', [RegisterController::class, 'saveRecord']); }); Route::middleware('auth:api')->group(function () { Route::get('users/list/page', [UserManagementController::class, 'index']); });

Step 7: Create Controllers

RegisterController

namespace App\Http\Controllers\Auth; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use App\Http\Controllers\Controller; use Illuminate\Support\Carbon; class RegisterController extends Controller { public function saveRecord(Request $request) { $request->validate(['email' => 'required|email|unique:users']); $user = new User([ 'name' => $request->first_name . ' ' . $request->last_name, 'email' => $request->email, 'join_date' => Carbon::now()->toDayDateTimeString(), 'role_name' => $request->role_name, 'password' => Hash::make($request->password), ]); $user->save(); return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'Registration successful' ]); } }

LoginController

namespace App\Http\Controllers\Auth; use Auth; use Session; use Carbon\Carbon; use App\Models\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class LoginController extends Controller { public function authenticate(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $user = Auth::user(); $user->update(['last_login' => Carbon::now()]); $token = $user->createToken($user->email)->accessToken; return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'Login successful', 'user_info' => $user, 'token' => $token ]); } return response()->json([ 'response_code' => 400, 'status' => 'error', 'message' => 'Login failed' ]); } }

UserManagementController

namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; class UserManagementController extends Controller { public function index() { $users = User::latest()->paginate(10); return response()->json([ 'response_code' => 200, 'status' => 'success', 'message' => 'User list fetched successfully', 'data_user_list' => $users ]); } }

Step 8: API Testing Endpoints

Use tools like Postman or Insomnia to test the following endpoints:

MethodURLDescription
POST/api/auth/register/saveRegister user
POST/api/auth/login/pushLogin user
GET/api/users/list/page?page=1 (with Bearer token)Get the users' list

Headers (for protected routes):

Accept: application/json Authorization: Bearer {access_token}

Conclusion

You’ve now successfully created a Laravel 10 REST API secured with Passport OAuth2 authentication. You can use this setup for mobile apps, SPA frontends, or third-party API consumers.


Souy Soeng

Souy Soeng

Our website teaches and reads PHP, Framework Laravel, and how to download Admin template sample source code free. Thank you for being so supportive!

Github

Post a Comment

CAN FEEDBACK
close