Laravel for Beginners: Setting Up Your First Project
A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.
A REST API in Laravel is really just routes that return JSON instead of HTML, plus a bit of discipline around status codes and validation. Here's how to build one that won't fall apart the moment a frontend team starts using it.
API routes live in routes/api.php and are automatically prefixed with /api. Laravel also disables session state on this group by default, which is exactly what you want for a stateless API.
Route::apiResource('posts', PostController::class);
That single line generates index, store, show, update, and destroy routes — the full CRUD set — pointing at PostController.
Eloquent models already serialize to JSON automatically, but wrap them in an API Resource so you control exactly what shape goes out over the wire — and never accidentally leak a column you didn't mean to expose:
php artisan make:resource PostResource
class PostResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'excerpt' => Str::limit($this->body, 120),
'published_at' => $this->published_at?->toDateString(),
];
}
}
Never trust the request body. Move validation into a dedicated Form Request class rather than inline in the controller — it keeps the controller readable and the rules reusable:
class StorePostRequest extends FormRequest
{
public function rules()
{
return [
'title' => ['required', 'string', 'max:255'],
'body' => ['required', 'string'],
];
}
}
Consistent status codes are what separate an API that's pleasant to consume from one that makes every client guess.
For a first-party SPA or mobile app, Laravel Sanctum gives you token-based auth without the overhead of a full OAuth server. Once installed, protect routes with a single middleware:
Route::middleware('auth:sanctum')->apiResource('posts', PostController::class);
That's genuinely most of what a production API needs on day one — resources, validation, correct status codes, and token auth. Everything else (rate limiting, versioning, pagination) layers on top of this foundation.
A complete first-day guide to Laravel — installation, folder structure, your first route, and your first migration.
One-to-many, many-to-many, polymorphic, and the N+1 query trap that catches almost every Laravel developer at least once.
Why anything that talks to the outside world belongs in a queued job, and how to dispatch, delay, and chain them correctly.