A REST API is the main foundation in modern application development, both for mobile apps and separate frontends (SPAs). Laravel provides very complete tools for building clean and structured REST APIs. In this tutorial, you'll learn to build a complete CRUD (Create, Read, Update, Delete) REST API using Laravel 10/11.
Preparing the Laravel Project
Make sure you already have a Laravel project. If not, create one with the following command:
composer create-project laravel/laravel laravel-api
cd laravel-api
php artisan serve
Create the model, migration, and resource controller all at once with a single command:
php artisan make:model Product -mcr
The -m flag creates the migration, -c creates the controller, and -r makes it a resource controller.
Creating the Migration and Model
Open the newly created migration file in database/migrations/ and add the columns you need:
public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->decimal('price', 10, 2);
$table->integer('stock')->default(0);
$table->timestamps();
});
}
Then edit the model app/Models/Product.php:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name',
'description',
'price',
'stock',
];
}
Run the migration:
php artisan migrate
This is only part of the article. For the full discussion, with examples and step-by-step details, you can read it on the original source:
How to Build a CRUD REST API in Laravel
More programming tutorials and developer tools are also available at dhiecoderweb.com.
Top comments (0)