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.
Look under the hood
Included source files
# 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).
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreProjectRequest;
use App\Http\Resources\ProjectResource;
use App\Models\Project;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
/** Thin controller: it asks the model layer for data and returns a Resource. Validation lives in the Form Request. */
class ProjectController extends Controller
{
public function index(Request $request): AnonymousResourceCollection
{
// Always start from the signed-in user's own projects: a user can never list somebody else's.
$projects = $request->user()->projects()->latest()->paginate(20);
return ProjectResource::collection($projects);
}
public function store(StoreProjectRequest $request): JsonResponse
{
$project = $request->user()->projects()->create($request->validated());
return (new ProjectResource($project))->response()->setStatusCode(201);
}
public function show(Request $request, Project $project): ProjectResource
{
// 404 (not 403) for other people's projects: the existence of the record is not revealed either.
abort_unless($project->user_id === $request->user()->id, 404);
return new ProjectResource($project);
}
}
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class StoreProjectRequest extends FormRequest
{
/** Being signed in is enough here; put finer rules (plans, limits) in this method. */
public function authorize(): bool
{
return $this->user() !== null;
}
/** @return array<string, array<int, mixed>> */
public function rules(): array
{
return [
'name' => [
'required', 'string', 'max:120',
// A user may not have two projects with the same name.
Rule::unique('projects')->where('user_id', $this->user()->id),
],
'description' => ['nullable', 'string', 'max:2000'],
];
}
}
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** The public shape of a project. Only fields listed here ever leave the server (never user_id or internal columns). */
class ProjectResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'created_at' => $this->created_at?->toIso8601String(),
];
}
}
<?php
use App\Http\Controllers\ProjectController;
use Illuminate\Support\Facades\Route;
// Every route needs a valid token. Throttling protects the API from loops and abuse.
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function (): void {
Route::get('/projects', [ProjectController::class, 'index']);
Route::post('/projects', [ProjectController::class, 'store']);
Route::get('/projects/{project}', [ProjectController::class, 'show']);
});
<?php
use App\Models\Project;
use App\Models\User;
use Laravel\Sanctum\Sanctum;
it('requires a token', function () {
$this->getJson('/api/projects')->assertUnauthorized();
});
it('creates a project and returns it', function () {
Sanctum::actingAs(User::factory()->create());
$this->postJson('/api/projects', ['name' => 'Website', 'description' => 'New site'])
->assertCreated()
->assertJsonPath('data.name', 'Website')
->assertJsonMissingPath('data.user_id');
});
it('lists only my projects', function () {
$me = User::factory()->create();
$other = User::factory()->create();
Project::factory()->for($me)->create(['name' => 'Mine']);
Project::factory()->for($other)->create(['name' => 'Theirs']);
Sanctum::actingAs($me);
$this->getJson('/api/projects')->assertOk()->assertJsonCount(1, 'data')->assertJsonPath('data.0.name', 'Mine');
});
it('does not reveal another user\'s project', function () {
$other = Project::factory()->for(User::factory())->create();
Sanctum::actingAs(User::factory()->create());
$this->getJson('/api/projects/'.$other->id)->assertNotFound();
});
it('validates the input', function (array $payload, string $field) {
Sanctum::actingAs(User::factory()->create());
$this->postJson('/api/projects', $payload)->assertUnprocessable()->assertJsonValidationErrors($field);
})->with([
'name is required' => [[], 'name'],
'name is too long' => [['name' => str_repeat('a', 121)], 'name'],
'description is too long' => [['name' => 'x', 'description' => str_repeat('a', 2001)], 'description'],
]);
it('refuses a duplicate name for the same user', function () {
$user = User::factory()->create();
Project::factory()->for($user)->create(['name' => 'Same']);
Sanctum::actingAs($user);
$this->postJson('/api/projects', ['name' => 'Same'])->assertUnprocessable()->assertJsonValidationErrors('name');
});
Update history
- 1.0.0
First release.