Creating a REST API in Laravel with authentication involves several steps, from setting up a new Laravel project to configuring authentication mechanisms. Below are the detailed steps to achieve this:
Step 1: Setting Up a New Laravel Project
1. Install Laravel via Composer:
composer create-project --prefer-dist laravel/laravel laravel-rest-api cd laravel-rest-api
2. Configure the Environment:
Update the `.env` file with your database credentials:
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
3. Migrate the Database:
php artisan migrate
Step 2: Installing and Setting Up Sanctum for Authentication
1. Install Laravel Sanctum:
composer require laravel/sanctum
2. Publish the Sanctum Configuration:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
3. Run the Sanctum Migrations:
php artisan migrate
4. Add 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, ],
5. Configure Sanctum:
Ensure `Sanctum` is configured in `config/sanctum.php`.
Step 3: Creating API Routes and Controllers
1. Create a Controller:
php artisan make:controller Api/AuthController
2. Define Routes:
Define the necessary routes in `routes/api.php`:
use App\Http\Controllers\Api\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']); Route::get('user', [AuthController::class, 'user']); });
3. Implement Authentication Logic:
Add methods to the `AuthController`:
namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use App\Models\User; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Auth; 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), ]); $token = $user->createToken('auth_token')->plainTextToken; return response()->json(['access_token' => $token, 'token_type' => 'Bearer']); } public function login(Request $request) { $request->validate([ 'email' => 'required|string|email', 'password' => 'required|string', ]); if (!Auth::attempt($request->only('email', 'password'))) { return response()->json(['message' => 'Invalid login details'], 401); } $user = User::where('email', $request->email)->firstOrFail(); $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']); } public function user(Request $request) { return response()->json($request->user()); } }
Step 4: Testing the API
1. Register a New User:
curl -X POST http://your-domain/api/register -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com", "password": "password", "password_confirmation": "password"}'
2. Log In:
curl -X POST http://your-domain/api/login -H "Content-Type: application/json" -d '{"email": "john@example.com", "password": "password"}'
3. Get User Information:
curl -X GET http://your-domain/api/user -H "Authorization: Bearer your_token"
4. Log Out:
curl -X POST http://your-domain/api/logout -H "Authorization: Bearer your_token"
This setup provides a basic REST API with authentication using Laravel Sanctum. You can expand this by adding more routes, controllers, and other features as needed.
Recommended Posts
Why Laravel is Still the Best Framework for Web Development in 2024
November 7, 2024
Why Is The Laravel PHP Framework Secure & Best?
August 28, 2024
How To Install Laravel 10 Using Composer?
July 19, 2024