Building a REST API with Laravel (Step-by-step API Development)

Building a REST API with Laravel - Step-by-step API Development

1. Install Laravel

First, install Laravel using Composer:

composer create-project laravel/laravel rest-api

2. Set Up Database

Configure your .env file with database details and run migrations:

php artisan migrate

3. Create a Model and Migration

Generate a model with a migration file:

php artisan make:model Post -m

Define schema in the migration file:

Schema::create('posts', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->text('content');
    $table->timestamps();
});

4. Create a Controller

Generate a resource controller:

php artisan make:controller PostController --api

5. Define API Routes

Modify routes/api.php:

use App\Http\Controllers\PostController;

Route::apiResource('posts', PostController::class);

6. Implement CRUD Methods

Modify PostController.php:

public function index() {
    return Post::all();
}

public function store(Request $request) {
    return Post::create($request->all());
}

public function show(Post $post) {
    return $post;
}

public function update(Request $request, Post $post) {
    $post->update($request->all());
    return $post;
}

public function destroy(Post $post) {
    $post->delete();
    return response()->json(['message' => 'Deleted successfully']);
}

7. Implement API Authentication

Use Laravel Sanctum for API authentication:

composer require laravel/sanctum

Publish Sanctum config:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

Add Sanctum middleware to api.php routes:

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('posts', PostController::class);
});

8. Test API with Postman

Use Postman to test the API endpoints.

9. Deploy API

Use Laravel Forge, Docker, or shared hosting to deploy the API.

10. Conclusion

By following these steps, you can build and deploy a secure REST API using Laravel. Stay updated for more Laravel development tips!

Published by Developer Sahayak - Helping Developers Solve PHP, Laravel, and Drupal Issues.

0 Comments