Tutorial . Framework

Build a REST API with Laravel from Scratch

Joy DeyJune 10, 20268 min read Laravel API Tutorial

Laravel is widely known for building full-stack web applications, but it's equally powerful when used as a backend framework to serve RESTful APIs. Whether you are building a backend for a mobile app, a single-page application (SPA), or a microservice architecture, Laravel provides all the tools you need out of the box.

In this tutorial, we will build a fully functional REST API with Laravel from scratch. We'll cover routing, controllers, models, migrations, and API resource classes to ensure our JSON responses are perfectly formatted.

Step 1: Setting up the Laravel Project

First, let's create a new Laravel project. Open your terminal and run:

composer create-project laravel/laravel my-api
cd my-api

Once inside the project, you can install Laravel's dedicated API scaffolding by running:

php artisan install:api

This command publishes the `api.php` route file and configures Laravel Sanctum for API token authentication (which we will cover later if needed).

Step 2: Database, Migration, and Model

Let's build an API to manage "Products". We need a model, a migration, and a controller. We can generate them all at once:

php artisan make:model Product -a

The `-a` flag creates the Model, Factory, Seeder, Migration, Controller, and Policy. For an API, you might specifically want an API controller, which you can generate with `--api`.

Open the generated migration file and add some columns to the `products` table:

public function up()
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('slug')->unique();
        $table->text('description')->nullable();
        $table->decimal('price', 8, 2);
        $table->timestamps();
    });
}

Run the migration to create the table:

php artisan migrate

Next, configure the `Product` model to allow mass assignment for these fields:

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

Step 3: Defining API Routes

Open the `routes/api.php` file. This is where we define our API endpoints. Laravel provides a convenient way to generate standard CRUD routes using `apiResource`:

use App\Http\Controllers\ProductController;

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

This single line registers all necessary routes: GET (index, show), POST (store), PUT/PATCH (update), and DELETE (destroy).

Step 4: Formatting Responses with API Resources

Returning raw Eloquent models directly from your controllers is not recommended because it couples your database schema to your API response. Instead, we use Eloquent API Resources.

php artisan make:resource ProductResource

Inside the generated `ProductResource.php`:

public function toArray($request)
{
    return [
        'id' => $this->id,
        'title' => $this->name,
        'slug' => $this->slug,
        'price' => (float) $this->price,
        'created_at' => $this->created_at->toDateTimeString(),
    ];
}

Step 5: Implementing the Controller

Now, let's tie it all together in the `ProductController`. We will fetch the data and return it using our `ProductResource`.

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

class ProductController extends Controller
{
    public function index()
    {
        return ProductResource::collection(Product::all());
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'required|string|unique:products,slug',
            'price' => 'required|numeric',
        ]);

        $product = Product::create($validated);
        return new ProductResource($product);
    }

    public function show(Product $product)
    {
        return new ProductResource($product);
    }
    
    // update and destroy methods omitted for brevity...
}

Conclusion

And that's it! In just a few steps, we created a fully functional REST API. Laravel's built-in tools like Eloquent, Form Requests, and API Resources make it incredibly easy to build robust and scalable backends.