Laravel is a robust PHP framework known for its simplicity and developer-friendly approach. In this tutorial, we’ll guide you through creating a REST API for managing products in Laravel 11. This step-by-step process includes setting up models, controllers, migrations, and routes to handle CRUD (Create, Read, Update, Delete) operations. Whether you’re building a small project or a scalable application, understanding RESTful APIs is essential for modern web development.
Introduction
The REST API we create will allow users to:
- Retrieve products: Fetch all or specific product details.
- Create products: Add new product entries with name, description, and price.
- Update products: Edit existing product details.
- Delete products: Remove product records.
Using Laravel’s php artisan
commands, you’ll easily generate models, controllers, and migrations to power your API. By the end, you’ll have endpoints ready for real-world use and testing with tools like Postman.
Step 1: Install Laravel
First, create a new Laravel project using Composer.
Navigate to the project directory:
Step 2: Configure the Database
Update the .env
file with your database connection details:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel_api DB_USERNAME=root DB_PASSWORD=
Step 3: Create the Product Model and Migration
Generate a model with a migration file:
Edit the migration file in database/migrations/YYYY_MM_DD_create_products_table.php
:
Step 4: Create the ProductController
Generate a controller:
Add the following code to app/Http/Controllers/ProductController.php
:
Step 5: Add API Routes
Open the routes/api.php
file and add the following:
use App\Http\Controllers\ProductController; Route::apiResource('products', ProductController::class);
Step 6: Enable Mass Assignment in the Model
Edit the Product
model (app/Models/Product.php
) to allow mass assignment:
Step 7: Test the API
Use tools like Postman or cURL to test the API endpoints:
- Get all products:
- Method:
GET
- URL:
/api/products
- Method:
- Create a new product:
- Method:
POST
- URL:
/api/products
- Body (JSON):
- Method:
- Get a specific product:
- Method:
GET
- URL:
/api/products/{id}
- Method:
- Update a product:
- Method:
PUT
- URL:
/api/products/{id}
- Body (JSON):
- Method:
- Delete a product:
- Method:
DELETE
- URL:
/api/products/{id}
- Method:
Summary
In this guide, we demonstrated how to create a REST API in Laravel 11 for product management. This included CRUD operations, HTTP methods, and testing APIs. Mastering this ensures seamless integration between your Laravel backend and frontend applications, enhancing user experiences and productivity. Start building now!