Skip to main content

Web frameworks · Intermediate · 25 min

Build a CRUD app with Laravel 13, Eloquent and Blade

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PHP 8.5 · Laravel 13.43 · SQLite · checked on php:8.5-cli

You will build a small events manager in Laravel 13 that lists, creates, edits and deletes events through an Eloquent model, a resource controller, a form request and Blade components, with a feature test that proves it.

On this page

CRUD stands for create, read, update and delete, the four things almost every admin screen does to a record. Laravel gives each of them a fixed place: a migration describes the table, an Eloquent model reads and writes rows, a resource controller has one method per action, a form request validates input, and Blade templates draw the pages. Once you have built one CRUD screen this way, every other one in a Laravel codebase looks familiar.

You build an events manager for a tech community: a list of upcoming events, a page per event, and forms to add, edit and delete them. It uses SQLite, the default in a new Laravel 13 project, so there is no database server to set up. Along the way you meet mass-assignment protection, which stops a form from writing to columns you did not mean to expose, and you finish with feature tests that run the whole flow in memory.

You need PHP 8.5 and Composer, installed as in How to install Laravel 13 on Ubuntu 26.04. The same commands work on macOS with PHP 8.5 and Composer from Homebrew.

Step 1 · Create the project

Create a fresh Laravel 13 project in a demo folder. The constraint ^13.0 keeps you on Laravel 13, and Composer picks the newest 13.x release:

Bash
cd ~
composer create-project laravel/laravel:^13.0 events-app --no-interaction
cd events-app
php artisan --version

The project's setup scripts run at the end of the install. They write .env with a new APP_KEY, create the empty SQLite file database/database.sqlite, and run the starter migrations, which add tables for users, sessions, cache and queued jobs.

Check it worked

php artisan --version prints Laravel Framework 13.43.0 or a later 13.x number. Run ls database and you see database.sqlite next to the migrations, factories and seeders folders.

Step 2 · Make the model, migration and factory

Artisan can create a model together with the files that support it. --migration adds the script that creates the table, and --factory adds a class that makes fake events for tests:

Bash
php artisan make:model Event --migration --factory

Laravel names the table after the model, in the plural: events. The migration's filename starts with a timestamp, so find it with a wildcard and replace its content with the columns an event needs:

Bash
MIGRATION="$(ls database/migrations/*_create_events_table.php)"
cat > "$MIGRATION" <<'PHP'
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->string('title', 120);
            $table->string('venue', 120);
            $table->dateTime('starts_at')->index();
            $table->unsignedInteger('capacity');
            $table->text('description')->nullable();
            $table->boolean('is_featured')->default(false);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('events');
    }
};
PHP

is_featured is a column that only staff should set, for example to pin an event to the top of a home page. Nobody filling in the public form should be able to change it, and the model is where you enforce that. Replace app/Models/Event.php:

Bash
cat > app/Models/Event.php <<'PHP'
<?php

namespace App\Models;

use Database\Factories\EventFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

#[Fillable(['title', 'venue', 'starts_at', 'capacity', 'description'])]
class Event extends Model
{
    /** @use HasFactory<EventFactory> */
    use HasFactory;

    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime',
            'capacity' => 'integer',
            'is_featured' => 'boolean',
        ];
    }
}
PHP

The #[Fillable] attribute lists the columns that Event::create($data) and $event->update($data) may write. Any other key in $data, such as is_featured, is dropped without an error. Older Laravel code does the same job with a protected $fillable = [...] property, and you will see both. The casts turn starts_at into a date object you can format, and is_featured into a real true or false.

Fill in the factory so tests can create realistic events in one line:

Bash
cat > database/factories/EventFactory.php <<'PHP'
<?php

namespace Database\Factories;

use App\Models\Event;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends Factory<Event>
 */
class EventFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => fake()->sentence(3),
            'venue' => fake()->city(),
            'starts_at' => fake()->dateTimeBetween('+1 week', '+3 months'),
            'capacity' => fake()->numberBetween(20, 300),
            'description' => fake()->paragraph(),
        ];
    }
}
PHP

Create the table, then ask Laravel to describe the model:

Bash
php artisan migrate
php artisan model:show Event

Check it worked

migrate prints a line ending in create_events_table and DONE. model:show prints the database (sqlite), the table (events) and an Attributes list. title, venue, starts_at, capacity and description carry the word fillable. is_featured does not, and shows its boolean cast.

Step 3 · Validate input with a form request

A form request is a class that holds the validation rules for one form. The controller receives it already validated, so the controller stays short. Create one:

Bash
php artisan make:request EventRequest

The generated authorize() method returns false, which refuses every request with a 403 until you change it. This app has no sign-in yet, so allow everyone, and add the rules:

Bash
cat > app/Http/Requests/EventRequest.php <<'PHP'
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class EventRequest extends FormRequest
{
    public function authorize(): bool
    {
        // Replace with a real check once the app has users, for example
        // return $this->user()?->can('manage-events') ?? false;
        return true;
    }

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:120'],
            'venue' => ['required', 'string', 'max:120'],
            'starts_at' => ['required', 'date'],
            'capacity' => ['required', 'integer', 'min:1', 'max:100000'],
            'description' => ['nullable', 'string', 'max:2000'],
        ];
    }

    public function attributes(): array
    {
        return ['starts_at' => 'start time'];
    }
}
PHP

attributes() changes how a field is named in error messages, so readers see "The start time field is required" rather than "starts at". The max:120 rule counts characters, not bytes, so a Yorùbá title full of tone marks or an Amharic venue name gets the same 120 characters as an English one. That matches the string('title', 120) column.

Check it worked

The file app/Http/Requests/EventRequest.php exists and php -l app/Http/Requests/EventRequest.php prints No syntax errors detected:

Bash
php -l app/Http/Requests/EventRequest.php

Step 4 · Add the resource controller and routes

A resource controller has seven methods, one for each page or action of a CRUD screen. --model=Event makes Artisan type-hint the model in each method, so Laravel looks up the event from the ID in the URL for you (route model binding):

Bash
php artisan make:controller EventController --model=Event --resource

Replace the generated methods with working ones:

Bash
cat > app/Http/Controllers/EventController.php <<'PHP'
<?php

namespace App\Http\Controllers;

use App\Http\Requests\EventRequest;
use App\Models\Event;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class EventController extends Controller
{
    public function index(): View
    {
        return view('events.index', [
            'events' => Event::orderBy('starts_at')->get(),
        ]);
    }

    public function create(): View
    {
        return view('events.create', ['event' => new Event]);
    }

    public function store(EventRequest $request): RedirectResponse
    {
        $event = Event::create($request->validated());

        return redirect()->route('events.show', $event)->with('status', 'Event created.');
    }

    public function show(Event $event): View
    {
        return view('events.show', ['event' => $event]);
    }

    public function edit(Event $event): View
    {
        return view('events.edit', ['event' => $event]);
    }

    public function update(EventRequest $request, Event $event): RedirectResponse
    {
        $event->update($request->validated());

        return redirect()->route('events.show', $event)->with('status', 'Event updated.');
    }

    public function destroy(Event $event): RedirectResponse
    {
        $event->delete();

        return redirect()->route('events.index')->with('status', 'Event deleted.');
    }
}
PHP

Three things protect the database here. $request->validated() returns only the fields that have rules, so an extra is_featured=1 in the form never reaches the model. #[Fillable] on the model drops it again if someone later writes Event::create($request->all()). And when validation fails, Laravel redirects back to the form with the errors and the old input before store or update runs at all. with('status', ...) flashes a message: it is stored in the session for the next request only, then removed.

Register all seven routes with one line at the end of routes/web.php:

Bash
cat >> routes/web.php <<'PHP'

Route::resource('events', \App\Http\Controllers\EventController::class);
PHP
php artisan route:list --path=events

Check it worked

route:list shows seven routes and ends with Showing [7] routes. They include GET|HEAD events named events.index, POST events (events.store), GET|HEAD events/{event}/edit (events.edit), PUT|PATCH events/{event} (events.update) and DELETE events/{event} (events.destroy).

Step 5 · Build the pages with Blade components

The controller asks for four views: events.index, events.show, events.create and events.edit. They share a page frame and a form field, so build those as Blade components first. An anonymous component is a Blade file in resources/views/components, used as an <x-name> tag:

Bash
mkdir -p resources/views/components resources/views/events
cat > resources/views/components/layout.blade.php <<'BLADE'
@props(['title' => 'Events'])
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>{{ $title }} · Events manager</title>
    <style>
        body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 0 auto; padding: 1rem; line-height: 1.5; }
        .status { background: #e7f4ea; border-left: 4px solid #2e7d32; padding: .5rem .75rem; }
        .error { color: #b00020; margin: .25rem 0 0; }
        label { display: block; margin-top: 1rem; font-weight: 600; }
        input, textarea { width: 100%; box-sizing: border-box; padding: .5rem; font: inherit; }
        button { margin-top: 1rem; padding: .5rem 1rem; font: inherit; }
    </style>
</head>
<body>
    <header><a href="{{ route('events.index') }}">Events manager</a></header>
    <main>
        @session('status')
            <p class="status" role="status">{{ $value }}</p>
        @endsession
        <h1>{{ $title }}</h1>
        {{ $slot }}
    </main>
</body>
</html>
BLADE

@props declares the component's inputs, with a default title. {{ $slot }} is where the content between <x-layout> and </x-layout> goes. @session('status') prints the flashed message, if there is one, as $value.

The field component draws a label, an input and its error message, and refills the input after a failed submit with old():

Bash
cat > resources/views/components/field.blade.php <<'BLADE'
@props(['name', 'label', 'type' => 'text', 'value' => null])
<label for="{{ $name }}">{{ $label }}</label>
@if ($type === 'textarea')
    <textarea id="{{ $name }}" name="{{ $name }}" rows="4" @error($name) aria-invalid="true" aria-describedby="{{ $name }}-error" @enderror {{ $attributes }}>{{ old($name, $value) }}</textarea>
@else
    <input id="{{ $name }}" name="{{ $name }}" type="{{ $type }}" value="{{ old($name, $value) }}" @error($name) aria-invalid="true" aria-describedby="{{ $name }}-error" @enderror {{ $attributes }}>
@endif
@error($name)
    <p class="error" id="{{ $name }}-error">{{ $message }}</p>
@enderror
BLADE

Any attribute that is not a prop, such as required or min="1", lands in $attributes and is printed on the input. The aria- attributes let screen readers announce the error with the field.

Now the shared form, used by both the create and the edit page. toDateTimeLocalString('minute') formats the date the way a datetime-local input expects, such as 2027-03-06T18:00:

Bash
cat > resources/views/events/_form.blade.php <<'BLADE'
@csrf
<x-field name="title" label="Title" :value="$event->title" required maxlength="120" />
<x-field name="venue" label="Venue" :value="$event->venue" required maxlength="120" />
<x-field name="starts_at" label="Starts at" type="datetime-local" :value="$event->starts_at?->toDateTimeLocalString('minute')" required />
<x-field name="capacity" label="Capacity" type="number" :value="$event->capacity" required min="1" />
<x-field name="description" label="Description (optional)" type="textarea" :value="$event->description" />
BLADE

@csrf adds a hidden token field. Laravel 13 accepts a form post when the browser's Sec-Fetch-Site header says it came from the same site, and falls back to checking that token for older browsers, so every form needs it.

The four pages:

Bash
cat > resources/views/events/index.blade.php <<'BLADE'
<x-layout title="Upcoming events">
    <p><a href="{{ route('events.create') }}">Add an event</a></p>
    @forelse ($events as $event)
        <article>
            <h2><a href="{{ route('events.show', $event) }}">{{ $event->title }}</a></h2>
            <p>{{ $event->starts_at->format('D j M Y, H:i') }} · {{ $event->venue }}</p>
        </article>
    @empty
        <p>No events yet.</p>
    @endforelse
</x-layout>
BLADE

cat > resources/views/events/show.blade.php <<'BLADE'
<x-layout :title="$event->title">
    <p>{{ $event->starts_at->format('l j F Y, H:i') }}<br>{{ $event->venue }} · {{ $event->capacity }} places</p>
    @if ($event->description)
        <p>{{ $event->description }}</p>
    @endif
    <p><a href="{{ route('events.edit', $event) }}">Edit this event</a></p>
    <form method="POST" action="{{ route('events.destroy', $event) }}">
        @csrf
        @method('DELETE')
        <button type="submit">Delete this event</button>
    </form>
</x-layout>
BLADE

cat > resources/views/events/create.blade.php <<'BLADE'
<x-layout title="New event">
    <form method="POST" action="{{ route('events.store') }}">
        @include('events._form')
        <button type="submit">Save event</button>
    </form>
</x-layout>
BLADE

cat > resources/views/events/edit.blade.php <<'BLADE'
<x-layout title="Edit event">
    <form method="POST" action="{{ route('events.update', $event) }}">
        @method('PUT')
        @include('events._form')
        <button type="submit">Save changes</button>
    </form>
</x-layout>
BLADE

HTML forms can only send GET and POST. @method('PUT') and @method('DELETE') add a hidden _method field, and Laravel routes the POST to update or destroy as if the browser had sent that method. The pages carry no JavaScript and only a few lines of inline CSS, so each one is a few kilobytes: quick on a low-end Android phone and cheap on prepaid mobile data.

Check it worked

Compile every Blade view. Any typo in a directive or component tag is reported here with the file name:

Bash
php artisan view:cache

It prints Blade templates cached successfully. Clear the compiled copies afterwards so later edits show up straight away:

Bash
php artisan view:clear

Step 6 · Run the app and try each action

Start the development server and keep it running in its own terminal:

Bash
php artisan serve

In a second terminal, from the events-app folder, request the list page:

Bash
curl -s http://127.0.0.1:8000/events | grep -E '<title>|No events yet'

The output shows <title>Upcoming events · Events manager</title> and <p>No events yet.</p>. Now open http://127.0.0.1:8000/events in a browser. On a remote server, forward the port from your own computer first with ssh -L 8000:127.0.0.1:8000 you@your-server, rather than opening port 8000 to the network.

  1. Choose Add an event. Fill in a title, venue, start time and a capacity of 80, then choose Save event.
  2. Add a second event, but type a single space as the title. The browser's own required check lets a space through, so the form posts, and you come back to the form with "The title field is required." under the title, your other values still filled in.
  3. Open an event, choose Edit this event, change the venue and save.
  4. Delete one event with Delete this event.

Check it worked

After step 1 the browser lands on the new event's page with a green "Event created." message, and a reload makes the message disappear, because flashed data lasts one request. The list page shows events in date order. After the edit you see "Event updated." and the new venue, and after the delete you are back on the list with "Event deleted.". Dates show in UTC, the default timezone set in config/app.php. Change 'timezone' => 'UTC' there to, for example, 'Africa/Lagos' or 'Africa/Nairobi' if all your users share one timezone.

Step 7 · Write feature tests

Feature tests send requests to the app in memory, with no server. The project's phpunit.xml points tests at an in-memory SQLite database, and the RefreshDatabase trait runs the migrations into it before each test, so your database.sqlite is never touched. Create a test class and replace its content:

Bash
php artisan make:test EventCrudTest
cat > tests/Feature/EventCrudTest.php <<'PHP'
<?php

namespace Tests\Feature;

use App\Models\Event;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class EventCrudTest extends TestCase
{
    use RefreshDatabase;

    private function validData(array $overrides = []): array
    {
        return array_merge([
            'title' => 'Lagos Laravel Meetup',
            'venue' => 'Yaba, Lagos',
            'starts_at' => '2027-03-06T18:00',
            'capacity' => '80',
            'description' => 'Two short talks, then questions.',
        ], $overrides);
    }

    public function test_index_lists_events(): void
    {
        Event::factory()->create(['title' => 'Ìpàdé àwọn olùgbéjáde PHP']);

        $this->get('/events')->assertOk()->assertSee('Ìpàdé àwọn olùgbéjáde PHP');
    }

    public function test_an_event_can_be_created(): void
    {
        $response = $this->post('/events', $this->validData());

        $event = Event::sole();
        $response->assertRedirect(route('events.show', $event));
        $response->assertSessionHas('status', 'Event created.');
        $this->assertSame('2027-03-06 18:00', $event->starts_at->format('Y-m-d H:i'));
    }

    public function test_invalid_input_is_rejected(): void
    {
        $this->from('/events/create')
            ->post('/events', $this->validData(['title' => '', 'capacity' => '0']))
            ->assertRedirect('/events/create')
            ->assertSessionHasErrors(['title', 'capacity']);

        $this->assertDatabaseCount('events', 0);
    }

    public function test_is_featured_cannot_be_mass_assigned(): void
    {
        $this->post('/events', $this->validData(['is_featured' => '1']));
        $this->assertFalse(Event::sole()->is_featured);

        $event = Event::create($this->validData(['is_featured' => true]));
        $this->assertFalse($event->fresh()->is_featured);
    }

    public function test_an_event_can_be_updated_and_deleted(): void
    {
        $event = Event::factory()->create();

        $this->put(route('events.update', $event), $this->validData(['title' => 'Accra Code Social']))
            ->assertRedirect(route('events.show', $event));
        $this->assertSame('Accra Code Social', $event->fresh()->title);

        $this->delete(route('events.destroy', $event))
            ->assertRedirect(route('events.index'));
        $this->assertModelMissing($event);
    }
}
PHP
php artisan test

test_is_featured_cannot_be_mass_assigned checks both layers: the form post, where validated() drops the field, and a direct Event::create(), where #[Fillable] drops it. Tests skip the CSRF check, which is why the posts work without a token.

Check it worked

Each test is listed with a pass mark, the five in EventCrudTest and the two starter tests, and the run ends with a line like Tests: 7 passed followed by the assertion count and a duration. To see a failure, add 'is_featured' to the #[Fillable] list in app/Models/Event.php and run php artisan test again: the mass-assignment test fails. Put the model back as it was before you go on.

Step 8 · Stop the server and clean up

Press Ctrl+C in the terminal running php artisan serve.

Keep ~/events-app if you want to carry on building it. Otherwise delete the demo folder, which holds the code and the SQLite database:

Bash
cd ~
rm -rf ~/events-app

Check it worked

ls ~/events-app reports No such file or directory, and nothing answers at http://127.0.0.1:8000. PHP and Composer stay installed for the next project.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.