Laravel API Development with Authentication

Build secure REST APIs with Laravel using Sanctum for authentication, implementing best practices for API design and security.

By Renie Namocot
10 min read
Laravel API Development with Authentication

Laravel API Development with Authentication

By Renie Namocot10 min read
LaravelPHPAPIAuthenticationSanctum
Laravel API Development with Authentication

Building RESTful APIs with Laravel

Laravel provides a robust framework for building secure and scalable REST APIs. In this guide, we'll explore how to create APIs with proper authentication using Laravel Sanctum.

Setting Up Laravel Sanctum

First, install and configure Laravel Sanctum for API authentication:

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate

API Route Structure

Organize your API routes in routes/api.php:

Route::post('/register', [AuthController::class, 'register']);
Route::post('/login', [AuthController::class, 'login']);

Route::middleware('auth:sanctum')->group(function () {
    Route::get('/user', function (Request $request) {
        return $request->user();
    });
    Route::apiResource('posts', PostController::class);
});

Authentication Controller

Create secure authentication endpoints:

public function login(Request $request)
{
    $request->validate([
        'email' => 'required|email',
        'password' => 'required',
    ]);

    if (Auth::attempt($request->only('email', 'password'))) {
        $user = Auth::user();
        $token = $user->createToken('API Token')->plainTextToken;
        
        return response()->json([
            'user' => $user,
            'token' => $token
        ]);
    }
    
    return response()->json(['message' => 'Invalid credentials'], 401);
}

API Resources

Use Laravel API Resources for consistent data formatting:

php artisan make:resource PostResource

class PostResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'content' => $this->content,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

Rate Limiting

Implement rate limiting to protect your API:

Route::middleware(['throttle:60,1'])->group(function () {
    // Your API routes here
});

Tags

#Laravel#PHP#API#Authentication#Sanctum
Renie Namocot

About Renie Namocot

Full-stack developer specializing in Laravel, Next.js, React, WordPress, and Shopify. Passionate about creating efficient, scalable web applications and sharing knowledge through practical tutorials.

Share this article

Laravel API Development with Authentication | Renie Namocot Blog