Writing

Restful API (Dynamic) in Laravel: Simplifying Large-Scale API Development

Oct 2023 · 5 min read


When an application grows, you often need the same CRUD endpoints for many models: list, show, create, update, delete. Writing a full controller for every model means a lot of copied code. A dynamic controller removes that repetition by serving several models through one class.

The route

routes/api.php

<?php

use App\Http\Controllers\Api\DynamicApiController;
use Illuminate\Support\Facades\Route;

Route::apiResource('v1/{resource}', DynamicApiController::class)
    ->where('resource', 'products|orders|customers');

The where clause is important. It whitelists exactly which resources the dynamic route may serve, so no one can ask for a model you did not expose.

The dynamic controller

app/Http/Controllers/Api/DynamicApiController.php

<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class DynamicApiController extends Controller
{
    private array $models = [
        'products'  => \App\Models\Product::class,
        'orders'    => \App\Models\Order::class,
        'customers' => \App\Models\Customer::class,
    ];

    public function index(string $resource)
    {
        $model = $this->resolveModel($resource);

        return $model::query()->latest()->paginate(15);
    }

    public function store(Request $request, string $resource)
    {
        $model = $this->resolveModel($resource);

        $data = $request->validate($model::rules());

        return response()->json($model::create($data), 201);
    }

    public function show(string $resource, int $id)
    {
        return $this->resolveModel($resource)::findOrFail($id);
    }

    public function update(Request $request, string $resource, int $id)
    {
        $model  = $this->resolveModel($resource);
        $record = $model::findOrFail($id);

        $record->update($request->validate($model::rules()));

        return response()->json($record);
    }

    public function destroy(string $resource, int $id)
    {
        $this->resolveModel($resource)::findOrFail($id)->delete();

        return response()->noContent();
    }

    private function resolveModel(string $resource): string
    {
        abort_unless(isset($this->models[$resource]), 404);

        return $this->models[$resource];
    }
}

Validation lives on the model

app/Models/Product.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

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

    public static function rules(): array
    {
        return [
            'name'  => ['required', 'string', 'max:120'],
            'price' => ['required', 'numeric', 'min:0'],
            'stock' => ['sometimes', 'integer', 'min:0'],
        ];
    }
}

Why it helps

Adding a new resource is now one line in the map and one line in the route whitelist, not a whole new controller. This pattern is great for admin panels and internal APIs with many simple models. When a resource grows and needs special logic, give it its own dedicated controller with Form Requests and API Resources, and take it out of the map.