Build RESTful API CRUD in Laravel 11 with Best Practices

Laravel 11 is a powerful PHP framework that simplifies the process of building RESTful APIs. In this blog, we’ll walk you through creating a CRUD (Create, Read, Update, Delete) application in Laravel 11 using best practices. We’ll cover everything from setting up your Laravel application to implementing the Repository design pattern, validation, and resource classes.

By the end of this guide, you’ll have a fully functional RESTful API built with Laravel 11, following industry best practices for scalability, maintainability, and security.


Step 1: Setting Up Laravel

To get started, create a new Laravel project using Composer:

composer create-project --prefer-dist laravel/laravel rest-api-crud

This command sets up a new Laravel project named rest-api-crud.


Step 2: Configure MySQL Database

By default, Laravel 11 uses SQLite. To switch to MySQL, update the .env file:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_database_name DB_USERNAME=your_username DB_PASSWORD=your_password

Step 3: Create the Product Model with Migration

Generate a model and migration for the Product entity:

php artisan make:model Product -a

This command creates a model, migration, factory, and seeder for the Product.


Step 4: Define the Migration

In the database/migrations/YYYY_MM_DD_HHMMSS_create_products_table.php file, define the schema:

public function up(): void { Schema::create('products', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('details'); $table->timestamps(); }); }

Step 5: Create Product Repository Interface

Create an interface for the Product repository to define the contract for the repository methods:

php artisan make:interface /Interfaces/ProductRepositoryInterface

Add the following code to ProductRepositoryInterface.php:

<?php namespace App\Interfaces; interface ProductRepositoryInterface { public function index(); public function getById($id); public function store(array $data); public function update(array $data, $id); public function delete($id); }

Step 6: Implement the Product Repository

Create a repository class that implements the ProductRepositoryInterface:

php artisan make:class /Repositories/ProductRepository

Add the following code to ProductRepository.php:

<?php namespace App\Repository; use App\Models\Product; use App\Interfaces\ProductRepositoryInterface; class ProductRepository implements ProductRepositoryInterface { public function index() { return Product::all(); } public function getById($id) { return Product::findOrFail($id); } public function store(array $data) { return Product::create($data); } public function update(array $data, $id) { return Product::whereId($id)->update($data); } public function delete($id) { Product::destroy($id); } }

Step 7: Bind Interface and Implementation

Bind the interface to its implementation in a service provider:

php artisan make:provider RepositoryServiceProvider

Update the register method in RepositoryServiceProvider.php:

public function register(): void { $this->app->bind(ProductRepositoryInterface::class, ProductRepository::class); }

Step 8: Request Validation

Create form request classes for validation:

php artisan make:request StoreProductRequest php artisan make:request UpdateProductRequest

Add validation rules to these classes as shown in the blog above.


Step 9: Create a Common API Response Class

Create a reusable response class to standardize API responses:

php artisan make:class /Classes/ApiResponseClass

Add the code provided in the blog to this class.


Step 10: Create Product Resource

Generate a resource class to transform the Product model into JSON:

php artisan make:resource ProductResource

Customize the toArray method as shown in the blog.


Step 11: Implement the Product Controller

Create a controller to handle API requests:

php artisan make:controller ProductController

Add the CRUD methods to the controller, as shown in the blog.


Step 12: Define API Routes

Publish the API route file and define routes for the ProductController:

php artisan install:api

Add the following to routes/api.php:

Route::apiResource('/products', ProductController::class);

Conclusion

By following these steps, you’ve built a RESTful API CRUD application in Laravel 11 using best practices like the Repository pattern, validation, and resource classes. This approach ensures your API is scalable, maintainable, and secure. Laravel 11’s powerful features make it an excellent choice for building modern APIs.

Start implementing these practices in your projects and take your Laravel API development to the next level!


FAQs Section

Laravel 11 API CRUD refers to the Create, Read, Update, and Delete operations using Laravel’s API resources, controllers, and database models.

You can create a RESTful API in Laravel 11 by setting up routes in `routes/api.php`, using controllers with API resource methods, and implementing authentication with Laravel Sanctum.

The best practice is to use the Repository pattern for separating business logic, API resource classes for structured responses, and form requests for validation.

Laravel 11 provides authentication via Laravel Sanctum and Laravel Passport, allowing you to secure API routes using middleware like `auth:sanctum`.

You can handle API errors using Laravel’s `Handler.php` exception file, returning JSON responses with proper status codes and error messages.
Previous: Laravel 12: New Features, Performance Boost & InstallationNext: Build a Laravel Chat App with Laravel Chatify: A Step-by-Step Guide

Share