Featured image of post How to Build a REST API with Laravel: A Complete Beginner's Guide

How to Build a REST API with Laravel: A Complete Beginner's Guide

A comprehensive tutorial on building RESTful APIs using Laravel, perfect for beginners. Learn routing, controllers, models, and database interactions.

How to Build a REST API with Laravel: A Complete Beginner’s Guide

Building a RESTful API is a fundamental skill for any modern web developer. Laravel, a powerful PHP framework, simplifies this process considerably. This guide provides a step-by-step approach for beginners, covering essential concepts and practical examples.

Prerequisites

Before we start, ensure you have:

  • PHP: Version 8.1 or higher installed.
  • Composer: The PHP dependency manager. https://getcomposer.org/
  • Laravel Installer: Run composer global require laravel/installer in your terminal.
  • MySQL or PostgreSQL: A database server.

Project Setup

  1. Create a new Laravel project: Open your terminal and navigate to your desired directory. Then, run:

    1
    
    laravel new my-api
    
  2. Navigate to the project directory:

    1
    
    cd my-api
    
  3. Start the development server:

    1
    
    php artisan serve
    

Defining Routes

Laravel uses elegant routing. Let’s define routes for creating, reading, updating, and deleting (CRUD) resources. Open routes/api.php:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;

Route::prefix('products')->group(function () {
    Route::get('/', [ProductController::class, 'index']);
    Route::post('/', [ProductController::class, 'store']);
    Route::get('/{id}', [ProductController::class, 'show']);
    Route::put('/{id}', [ProductController::class, 'update']);
    Route::delete('/{id}', [ProductController::class, 'destroy']);
});

This defines routes for /api/products using resource-based routing for better organization.

Creating a Controller

We’ll need a controller to handle requests. Generate a controller using the Artisan CLI:

1
php artisan make:controller ProductController --resource --api

This creates a ProductController with basic CRUD methods. You can customize these methods based on your needs. For example, a store method might look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric',
            'description' => 'string',
        ]);

        $product = Product::create($validated);

        return response()->json($product, 201);
    }
}

This validates the incoming request data and creates a new product in the database.

Creating a Model

Laravel uses Eloquent ORM for database interactions. Generate a model:

1
php artisan make:model Product

This creates a Product model. You’ll need to define the database table it interacts with and its attributes. In app/Models/Product.php:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
    protected $fillable = ['name', 'price', 'description'];
}

This makes name, price, and description mass-assignable. Remember to create the corresponding database migration and run it.

Testing Your API

Use tools like Postman or curl to test your API endpoints. For example, to create a new product, send a POST request to /api/products with the necessary data in the request body (JSON format).

Conclusion

This guide offers a foundational understanding of building REST APIs with Laravel. Explore Laravel’s documentation for more advanced features like authentication, middleware, and relationships. Remember to always validate user inputs to prevent security vulnerabilities. This is a starting point, and continuous learning is key to becoming proficient in API development.