Navigation

Laravel

How to use `apiResource` for RESTful controllers

Create complete RESTful API routes in Laravel with a single line using apiResource. Automatically generates all CRUD endpoints except create and edit forms.

Table Of Contents

Problem

You need to create full CRUD API routes for a resource but don't want to write each route manually (GET, POST, PUT, DELETE).

Solution

Use Route::apiResource() to generate all API routes automatically:

// routes/api.php
Route::apiResource('users', UserController::class);

// This generates:
// GET    /api/users           -> index()
// POST   /api/users           -> store()
// GET    /api/users/{user}    -> show()
// PUT    /api/users/{user}    -> update()
// DELETE /api/users/{user}    -> destroy()

Create the controller with API methods:

php artisan make:controller UserController --api

Generated controller structure:

<?php

namespace App\Http\Controllers;

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

class UserController extends Controller
{
    public function index()
    {
        return User::all();
    }

    public function store(Request $request)
    {
        $user = User::create($request->validated());
        return response()->json($user, 201);
    }

    public function show(User $user)
    {
        return $user;
    }

    public function update(Request $request, User $user)
    {
        $user->update($request->validated());
        return $user;
    }

    public function destroy(User $user)
    {
        $user->delete();
        return response()->json(null, 204);
    }
}

Why It Works

apiResource creates routes optimized for APIs by excluding create and edit routes (which return forms for web apps). It automatically applies route model binding and uses standard HTTP verbs for RESTful operations.

Customize which routes to include/exclude:

// Only specific actions
Route::apiResource('users', UserController::class)->only(['index', 'show']);

// Exclude specific actions
Route::apiResource('users', UserController::class)->except(['destroy']);

// Multiple resources
Route::apiResources([
    'users' => UserController::class,
    'posts' => PostController::class,
]);

Related: Laravel Collections: Beyond Basic Array Operations | Laravel Events and Listeners: Building Decoupled Applications | Laravel API Development: Best Practices and Security | REST API Guide for Beginners: Build Better APIs in 2025 | REST API Design Best Practices Tutorial 2025

Share this article

Add Comment

No comments yet. Be the first to comment!

More from Laravel