Laravel examples Free template

Laravel JSON API resource

A complete, tested example of a Laravel API endpoint set: routes, controller, form request, API resource and Pest tests.

About this template

Everything for one well-built API resource in Laravel 11+ (written for Laravel 13): routes grouped under auth:sanctum, a controller that only coordinates, a Form Request that validates and authorises, an API Resource that shapes the JSON, and Pest feature tests that cover creating, listing, ownership (one user cannot read another user's data) and validation errors. Copy the files into your app, add a Project model and migration (shown in the README), and you have a pattern to repeat for other resources. This is a code example to read and copy; it does not run in the browser.

laravelapirestpestvalidationsanctum

Look under the hood

Included source files

1,417 bytes
# Laravel JSON API resource

A pattern for one API resource ("projects") with ownership checks and tests.

## Install

1. Create the model and migration:

   ```bash
   php artisan make:model Project -m
   ```

   In the migration:

   ```php
   Schema::create('projects', function (Blueprint $table) {
       $table->id();
       $table->foreignId('user_id')->constrained()->cascadeOnDelete();
       $table->string('name', 120);
       $table->text('description')->nullable();
       $table->timestamps();
   });
   ```

   In `app/Models/Project.php` add `protected $fillable = ['name', 'description'];` and a `user()` relation.
   In `app/Models/User.php` add `public function projects(): HasMany { return $this->hasMany(Project::class); }`.

2. Copy the files of this template into your app, keeping the folders.
3. Install Sanctum if you do not have it: `php artisan install:api`.
4. Run the tests: `php artisan test --filter=ProjectApiTest`.

## Endpoints

| Method | URL | What it does |
| --- | --- | --- |
| GET | /api/projects | List the signed-in user's projects (paginated) |
| POST | /api/projects | Create a project |
| GET | /api/projects/{id} | Show one of your projects |

## Ideas for next steps

- Add update and delete with the same ownership rule.
- Add filtering with a `?search=` query parameter.
- Return the same error format for every failure (see `bootstrap/app.php` exception rendering).

Update history

  1. 1.0.0

    First release.