User Login with API Using Laravel 11
Hello Artisans, making User Login with API Using Laravel 11 is very easy, In this blog, i will complete explain you that how you can implement and create a User Login with API Using Laravel 11, This in detailed Laravel API for User Creations involves setting up authentication, creating the necessary routes, controllers, and request handling.
Step 1: Install Laravel Sanctum
Laravel Sanctum provides a lightweight authentication system for SPAs (single page applications), mobile applications, and simple, token-based APIs.
First, install Sanctum via Composer:
composer require laravel/sanctum
Step 2: Publish the Sanctum Configuration
Publish the Sanctum configuration file using the following command:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
Configure Database First and Then we will do migrations:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_database_username DB_PASSWORD=your_database_password
Run the Sanctum migrations:
php artisan migrate
Read Also:
Step 3: Configure Sanctum Middleware
Add Sanctum’s middleware to your api
middleware group within your app/Http/Kernel.php
file:
'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],
Step 4: Update User Model
Ensure your User
model uses the HasApiTokens
trait provided by Sanctum:
namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // Other model properties and methods }
Step 5: Create Auth Controller
Create an AuthController
to handle user registration, login, and logout:
php artisan make:controller AuthController
In AuthController.php
, implement the following methods:
namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; class AuthController extends Controller { public function register(Request $request) { $request->validate([ 'name' => 'required|string|max:255', 'email' => 'required|string|email|max:255|unique:users', 'password' => 'required|string|min:8|confirmed', ]); $user = User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => Hash::make($request->password), ]); return response()->json(['message' => 'User registered successfully']); } public function login(Request $request) { $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { throw ValidationException::withMessages([ 'email' => ['The provided credentials are incorrect.'], ]); } $token = $user->createToken('auth_token')->plainTextToken; return response()->json(['access_token' => $token, 'token_type' => 'Bearer']); } public function logout(Request $request) { $request->user()->tokens()->delete(); return response()->json(['message' => 'Logged out successfully']); } }
Step 6: Define Routes
Add routes for user registration, login, and logout in routes/api.php
:
use App\Http\Controllers\AuthController; Route::post('register', [AuthController::class, 'register']); Route::post('login', [AuthController::class, 'login']); Route::middleware('auth:sanctum')->group(function () { Route::post('logout', [AuthController::class, 'logout']); });
Step 7: Test Your API
You can use tools like Postman or cURL to test your API endpoints.
- POST /api/register: Register a new user.
- POST /api/login: Login a user.
- POST /api/logout: Logout a user (requires authentication).
In this blog, we have covered about API generation in Laravel, User Login API generation in Laravel