Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 67 ยท Projects

Project: A Task Manager with Livewire

Build a task manager with Livewire in Laravel 13, with a create form, live search and filters, policies, a status workflow and queued reminders, plus tests.

This project builds a task manager where each person sees only their own tasks. You can add a task with an optional due date, search and filter the list while you type, move a task through todo, doing and done, and get a reminder shortly before a task is due. There is no JavaScript to write: the interface is Livewire, and the interesting rules (who may touch a task, which status changes are allowed, which reminders should still be sent) live in PHP where you can test them.

Laravel and Livewire cannot run on this site, so the framework code below is read-only; copy it into a Laravel 13 app that has Livewire installed (composer require livewire/livewire, or pick the Livewire starter kit). The runnable examples are plain PHP stand-ins for the rules, so you can experiment with the logic. Each section says which is which.

The plan

flowchart TD
    F["CreateTask component<br/>form + validation"] --> DB[("tasks table")]
    L["TaskList component<br/>search, status filter, paging"] --> DB
    L --> P["TaskPolicy<br/>owner only"]
    F --> J["SendTaskReminder job<br/>delayed until due time - 1 hour"]
    J --> N["Notification to the owner"]

Two components share one table; the policy guards every change, and a delayed job sends the reminder.

The data model is small. Create it with php artisan make:model Task --migration --factory --policy:

PHP
Schema::create('tasks', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained()->cascadeOnDelete();
    $table->string('title', 120);
    $table->string('status', 10)->default('todo');
    $table->dateTime('due_at')->nullable();
    $table->dateTime('completed_at')->nullable();
    $table->timestamps();

    $table->index(['user_id', 'status']);
});

Store the status as a backed enum, so only valid values exist and the workflow rules have a home:

PHP
namespace App\Enums;

enum TaskStatus: string
{
    case Todo = 'todo';
    case Doing = 'doing';
    case Done = 'done';

    /** @return list<self> */
    public function allowedNext(): array
    {
        return match ($this) {
            self::Todo => [self::Doing],
            self::Doing => [self::Todo, self::Done],
            self::Done => [self::Todo],
        };
    }
}
PHP
class Task extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'due_at'];

    protected function casts(): array
    {
        return [
            'status' => TaskStatus::class,
            'due_at' => 'datetime',
            'completed_at' => 'datetime',
        ];
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function moveTo(TaskStatus $next): void
    {
        if (! in_array($next, $this->status->allowedNext(), true)) {
            throw new DomainException("Cannot move a task from {$this->status->value} to {$next->value}.");
        }

        $this->status = $next;
        $this->completed_at = $next === TaskStatus::Done ? now() : null;
        $this->save();
    }
}

Neither status nor user_id is fillable: clients can never set them in a form request body, only through moveTo() and through the owner's relationship. (Casts are covered in accessors, mutators and casts.)

The same state machine, runnable. The stand-in keeps the allowed transitions in the enum and a small log of what happened, with days counted by a fake clock:

PHP A task status state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

stateDiagram-v2
    [*] --> todo
    todo --> doing
    doing --> todo
    doing --> done
    done --> todo

The allowed status changes. Jumping straight from todo to done, or from done back to doing, is refused.

The create form component

Generate a component with php artisan make:livewire create-task. Livewire 4 can keep the PHP class and the template together in one file, or in two (the --class option gives the classic layout); this lesson shows the classic class form, and the template is the same either way.

PHP
namespace App\Livewire;

use Livewire\Attributes\Validate;
use Livewire\Component;

class CreateTask extends Component
{
    #[Validate('required|string|max:120')]
    public string $title = '';

    #[Validate('nullable|date|after:now')]
    public ?string $dueAt = null;

    public function save(): void
    {
        $this->validate();

        $task = auth()->user()->tasks()->create([
            'title' => $this->title,
            'due_at' => $this->dueAt,
        ]);

        if ($task->due_at !== null) {
            SendTaskReminder::dispatch($task, $task->due_at->toIso8601String())
                ->delay($task->due_at->copy()->subHour());
        }

        $this->reset('title', 'dueAt');
        $this->dispatch('task-created');
    }

    public function render()
    {
        return view('livewire.create-task');
    }
}
BLADE
<form wire:submit="save" class="flex gap-2">
    <div>
        <input type="text" wire:model="title" placeholder="What needs doing?">
        @error('title') <p class="text-red-600">{{ $message }}</p> @enderror
    </div>
    <input type="datetime-local" wire:model="dueAt">
    @error('dueAt') <p class="text-red-600">{{ $message }}</p> @enderror
    <button type="submit">Add</button>
</form>

wire:model without .live only sends the value along with the next action, so typing does not cause a request per key press; validation errors appear when the form is submitted. Livewire runs save() on the server, shows the errors from the same @error directives you know from Blade forms, and re-renders just the form. After saving, the component dispatches a task-created browser event, which the list can listen for.

The list with live search and filters

PHP
namespace App\Livewire;

use App\Enums\TaskStatus;
use App\Models\Task;
use Livewire\Attributes\Computed;
use Livewire\Attributes\On;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;

class TaskList extends Component
{
    use WithPagination;

    #[Url(as: 'q')]
    public string $search = '';

    #[Url]
    public string $status = 'all';

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatus(): void
    {
        $this->resetPage();
    }

    #[Computed]
    public function tasks()
    {
        return auth()->user()->tasks()
            ->when($this->search !== '', fn ($query) => $query->where('title', 'like', '%'.$this->search.'%'))
            ->when($this->status !== 'all', fn ($query) => $query->where('status', $this->status))
            ->latest('id')
            ->paginate(10);
    }

    public function advance(int $taskId, string $next): void
    {
        $task = Task::findOrFail($taskId);

        $this->authorize('update', $task);

        $task->moveTo(TaskStatus::from($next));
    }

    #[On('task-created')]
    public function refreshAfterCreate(): void
    {
        $this->resetPage();
    }

    public function render()
    {
        return view('livewire.task-list');
    }
}
BLADE
<div>
    <input type="search" wire:model.live.debounce.300ms="search" placeholder="Search tasks">

    <select wire:model.live="status">
        <option value="all">All</option>
        @foreach (App\Enums\TaskStatus::cases() as $case)
            <option value="{{ $case->value }}">{{ ucfirst($case->value) }}</option>
        @endforeach
    </select>

    @forelse ($this->tasks as $task)
        <div wire:key="task-{{ $task->id }}">
            {{ $task->title }} ({{ $task->status->value }})
            @foreach ($task->status->allowedNext() as $next)
                <button wire:click="advance({{ $task->id }}, '{{ $next->value }}')">{{ $next->value }}</button>
            @endforeach
        </div>
    @empty
        <p>No tasks match.</p>
    @endforelse

    {{ $this->tasks->links() }}
</div>

Four details deserve attention:

  • wire:model.live.debounce.300ms sends the search text to the server 300 ms after the last key press, so fast typing makes one request instead of ten. The table then re-renders from the server's answer.
  • #[Url] writes the search and filter into the query string (?q=milk&status=doing), so a reload or a shared link restores the same view. Because the values come from the URL, treat them as untrusted input: like is parameter-bound, and status is compared as a plain string.
  • #[Computed] makes $this->tasks a cached, read-only value for one render, which keeps queries out of render() and out of the component's public state.
  • wire:key gives every row a stable identity, so Livewire updates the right row when the list changes.

The next example is a stand-in for the filtering and for the reminders that go with it. It uses a plain array of tasks, a TaskList object with search and status properties, and a reminder queue that runs with a fake clock in minutes. Notice what the reminder job does when it finally runs: it checks that the task still needs a reminder.

PHP Live filtering and stale reminders

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The reminder job in real Laravel does the same check. A delayed job cannot be edited once it is queued, so when someone changes the due date or completes the task, the old job still wakes up later. Instead of hunting it down in the queue, let it decide at run time whether it is still relevant:

PHP
namespace App\Jobs;

use App\Enums\TaskStatus;
use App\Models\Task;
use App\Notifications\TaskDueSoon;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\SerializesModels;

class SendTaskReminder implements ShouldQueue
{
    use Queueable, SerializesModels;

    public bool $deleteWhenMissingModels = true;

    public function __construct(public Task $task, public string $dueAtWhenQueued)
    {
    }

    public function handle(): void
    {
        $task = $this->task->fresh();

        if ($task === null
            || $task->status === TaskStatus::Done
            || $task->due_at?->toIso8601String() !== $this->dueAtWhenQueued) {
            return;
        }

        $task->user->notify(new TaskDueSoon($task));
    }
}

deleteWhenMissingModels silently drops the job if the task was deleted before the worker ran. The job is also safe to run twice (a retry cannot send a different message), but you can add ShouldBeUnique if duplicates would annoy users. Delayed jobs need a real queue driver and a running worker; read queues and jobs for queue:work and deployment notes, and notifications for the TaskDueSoon class.

Authorization: never trust the browser

Every Livewire action is an HTTP request that anyone can forge, including advance(42, 'done') for a task that is not theirs. Hiding a button in the template protects nobody. The advance() method therefore calls $this->authorize('update', $task), backed by this policy:

PHP
class TaskPolicy
{
    public function update(User $user, Task $task): bool
    {
        return $user->id === $task->user_id;
    }
}

Laravel finds TaskPolicy by naming convention, and authorize() throws an authorization exception (a 403) when the method returns false. Because Task::findOrFail($taskId) loads by ID, the policy check is what stops a stranger from advancing someone else's task. See gates and policies for more.

Tests

Livewire has its own test helper that drives a component without a browser:

PHP
use App\Livewire\CreateTask;
use App\Livewire\TaskList;
use App\Jobs\SendTaskReminder;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Queue;
use Livewire\Livewire;

uses(Illuminate\Foundation\Testing\RefreshDatabase::class);

it('requires a title', function () {
    Livewire::actingAs(User::factory()->create())
        ->test(CreateTask::class)
        ->set('title', '')
        ->call('save')
        ->assertHasErrors(['title' => 'required']);
});

it('queues a reminder for tasks with a due date', function () {
    Queue::fake();

    Livewire::actingAs(User::factory()->create())
        ->test(CreateTask::class)
        ->set('title', 'Pay rent')
        ->set('dueAt', now()->addDay()->format('Y-m-d\TH:i'))
        ->call('save')
        ->assertHasNoErrors();

    Queue::assertPushed(SendTaskReminder::class);
});

it('filters the list by search text', function () {
    $user = User::factory()->create();
    Task::factory()->for($user)->create(['title' => 'Buy milk']);
    Task::factory()->for($user)->create(['title' => 'Call the bank']);

    Livewire::actingAs($user)
        ->test(TaskList::class)
        ->set('search', 'milk')
        ->assertSee('Buy milk')
        ->assertDontSee('Call the bank');
});

it('does not let users advance other people\'s tasks', function () {
    $task = Task::factory()->create();

    Livewire::actingAs(User::factory()->create())
        ->test(TaskList::class)
        ->call('advance', $task->id, 'doing')
        ->assertForbidden();

    expect($task->fresh()->status->value)->toBe('todo');
});

The last test is the most valuable one: it proves the policy works even when the request is forged. The model's moveTo() rule deserves a plain unit test of its own, like the stand-in above.

Ideas to extend it

  • Add tasks to a project or a list, and use route model binding for a detail page.
  • Show a count per status with a withCount-style query and update it when tasks move.
  • Use a scheduled command to email a daily digest of overdue tasks.
  • Add team sharing with roles from roles and permissions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does wire:model.live.debounce.300ms do on a search input?

    .live syncs on input, and .debounce.300ms waits for a pause, so fast typing makes one request instead of many.
  2. 2. Why does advance() call $this->authorize() even though the button is hidden for other people's tasks?

    Anyone can send a request that calls advance() with any task ID. Only a server-side check, such as a policy, protects the data.
  3. 3. A reminder job is queued for 9:00 and the user then marks the task done at 8:00. What is the best design?

    Queued jobs cannot easily be edited. Checking the current state in handle() keeps stale reminders from being sent, and the job stays safe to retry.
  4. 4. What does the #[Url] attribute on a Livewire property do?

    #[Url] binds the property to a query string parameter, so ?q=milk restores the search. Treat such values as untrusted input.
  5. 5. Why is the status stored as a backed enum with an allowedNext() method?

    An enum limits the possible values and gives the transition rules a home, so models, components and tests share one definition.

Summary

  • Two Livewire components share one tasks table: a form (CreateTask) and a list (TaskList) with wire:model.live.debounce, #[Url] and pagination.
  • Put business rules, such as allowed status changes, in an enum and a model method, where plain unit tests can reach them.
  • Always authorize inside Livewire actions: the browser can send any action with any ID.
  • Delayed jobs cannot be edited, so let them check at run time whether they are still relevant, and make them safe to retry.
  • Test components with Livewire::test(), Queue::fake() and actingAs(), including the forged-request case.

Next: Project: A URL Shortener with Queues and Caching