Best Practices for Documenting Laravel Code
Laravel relies on PHP features and framework conventions, so a method’s signature (its name, parameters, and return type) does not always show…
A to-do app is a straightforward way to see how Laravel receives form data, saves it to a database, and displays it on the page. Visitors can add tasks, edit them, mark them complete, and delete them. Laravel builds the HTML pages on the server using Blade templates, a setup known as server-side rendering.
A route connects a URL to a controller, which is the code that handles a request. An Eloquent model lets PHP work with task rows in the database. A migration describes the database table’s structure, and Laravel’s validation checks form data before the controller saves it.
The code below targets Laravel 13, which requires PHP 8.3 or later, as listed in the Laravel 13 release notes. This version has no login system, so anyone who can reach the app sees the same task list. You will need to add authentication and ownership checks before using it for private, multi-user tasks.
Start by creating a new Laravel project, moving into its directory, and running the local development server:
composer create-project laravel/laravel todo-app
cd todo-app
php artisan serve
Next, configure your database connection in the project’s .env file and make sure Laravel can reach it. You will run a migration in the next step to create the tasks table there.
You can generate both the Task model and its migration with a single Artisan command:
php artisan make:model Task -m
A migration describes a database change in code so you can track it in version control. Open the new file in database/migrations and define the tasks table:
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('tasks', function (Blueprint $table) {
$table->id();
$table->string('title', 255);
$table->text('description')->nullable();
$table->boolean('is_completed')->default(false);
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('tasks');
}
};
Here, the title column allows up to 255 characters. The optional description column has no database-level length limit, though the controller will cap it at 2,000 characters during form validation. Because is_completed defaults to false, every new task starts as incomplete. You can read more about table columns and schema changes in Laravel’s migration documentation.
Run the migration to create the table in your database:
php artisan migrate
Next, update the model in app/Models/Task.php:
'boolean',
];
}
}
The Fillable attribute tells Eloquent which fields the controller is allowed to assign together when it creates or updates a task. Because the controller only passes fields that Laravel has validated, an unexpected field in a request cannot overwrite other columns. Laravel covers this in its documentation on mass assignment and Eloquent models.
Next, create a controller to list tasks, handle form submissions, and update records:
php artisan make:controller TaskController
Register the routes in routes/web.php:
use App\Http\Controllers\TaskController;
use Illuminate\Support\Facades\Route;
Route::get('/tasks', [TaskController::class, 'index'])->name('tasks.index');
Route::post('/tasks', [TaskController::class, 'store'])->name('tasks.store');
Route::get('/tasks/{task}/edit', [TaskController::class, 'edit'])->name('tasks.edit');
Route::put('/tasks/{task}', [TaskController::class, 'update'])->name('tasks.update');
Route::patch('/tasks/{task}/toggle', [TaskController::class, 'toggle'])->name('tasks.toggle');
Route::delete('/tasks/{task}', [TaskController::class, 'destroy'])->name('tasks.destroy');
Each route maps an incoming URL and HTTP method to a method on TaskController. When a URL includes {task}, Laravel looks up the matching task in the database automatically and returns a 404 response if no record exists.
Replace the contents of app/Http/Controllers/TaskController.php with the following code:
orderBy('is_completed')
->latest()
->get();
return view('tasks.index', compact('tasks'));
}
public function store(Request $request): RedirectResponse
{
$validated = $request->validate([
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:2000'],
]);
Task::create($validated);
return redirect()
->route('tasks.index')
->with('status', 'Task added.');
}
public function edit(Task $task): View
{
return view('tasks.edit', compact('task'));
}
public function update(Request $request, Task $task): RedirectResponse
{
$validated = $request->validate([
'title' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string', 'max:2000'],
'is_completed' => ['required', 'boolean'],
]);
$task->update($validated);
return redirect()
->route('tasks.index')
->with('status', 'Task updated.');
}
public function toggle(Task $task): RedirectResponse
{
$task->is_completed = ! $task->is_completed;
$task->save();
return redirect()->route('tasks.index');
}
public function destroy(Task $task): RedirectResponse
{
$task->delete();
return redirect()
->route('tasks.index')
->with('status', 'Task deleted.');
}
}
In index(), the query places incomplete tasks ahead of completed ones, then orders each group from newest to oldest. The toggle() method flips a task’s is_completed value and saves the change. When the controller creates or updates a task, it validates the title and description on the server because browser-side form rules alone cannot protect your database. If Laravel rejects the input, it redirects the visitor back to the form with their submitted values and the validation errors, which Blade’s @error directive displays next to each field. For more details, see Laravel’s validation documentation.
With the routes and controller in place, create the main view at resources/views/tasks/index.blade.php:
<title>Tasks</title>
<main>
<h1>Tasks</h1>
@if (session('status'))
{{ session('status') }}
@endif
<h2>Add a task</h2>
@csrf
<div>
<label for="title">Title</label>
@error('title')
{{ $message }}
@enderror
</div>
<div>
<label for="description">Description</label>
<textarea id="description" name="description">{{ old('description') }}</textarea>
@error('description')
{{ $message }}
@enderror
</div>
<button type="submit">Add task</button>
<h2>Task list</h2>
@forelse ($tasks as $task)
<article>
<h3>{{ $task->title }}</h3>
@if ($task->description)
{{ $task->description }}
@endif
Status: {{ $task->is_completed ? 'Completed' : 'Incomplete' }}
@csrf
@method('PATCH')
<button type="submit">
{{ $task->is_completed ? 'Mark incomplete' : 'Mark complete' }}
</button>
<a href="{{ route('tasks.edit', $task) }}">Edit</a>
@csrf
@method('DELETE')
<button type="submit">Delete</button>
</article>
@empty
No tasks yet. Add one above.
@endforelse
</main>
Blade’s {{ ... }} syntax escapes task text before Laravel renders it on the page. Always use it for visitor-submitted fields like titles and descriptions. Each form also includes @csrf, which adds a hidden token that Laravel checks to reject forged requests from outside your site. Because standard HTML forms only send GET and POST requests, @method adds a hidden field that tells Laravel to treat the request as a PATCH or DELETE. You can read more about escaped output in the Blade documentation and about form tokens in Laravel’s CSRF documentation.
To let visitors update existing tasks, create resources/views/tasks/edit.blade.php:
<title>Edit task</title>
<main>
<h1>Edit task</h1>
@csrf
@method('PUT')
<div>
<label for="title">Title</label>
title) }}"
maxlength="255"
required
>
@error('title')
{{ $message }}
@enderror
</div>
<div>
<label for="description">Description</label>
<textarea id="description" name="description">{{ old('description', $task->description) }}</textarea>
@error('description')
{{ $message }}
@enderror
</div>
<label>
is_completed))
>
Completed
</label>
<button type="submit">Save changes</button>
<a href="{{ route('tasks.index') }}">Back to tasks</a>
</main>
If a visitor leaves the checkbox unchecked, the hidden input submits 0; if they check it, the checkbox submits 1. That way, the controller always receives a completion value to validate. When validation fails, the old() helper refills the form with whatever the visitor just submitted. On a fresh visit, it falls back to the values saved on the task.
Open /tasks in your browser to test the app manually. Add a task with a title, then submit the form with a blank title. The first request should save a new row to the database, and the second should return you to the form with an error message under the title field. Try editing a task, toggling its completion status, and deleting it as well.
You can also verify these flows automatically with Laravel feature tests, which send web requests through your app and check both the responses and the database. Add the following test file at tests/Feature/TaskTest.php to cover valid task creation and a rejected submission:
post(route('tasks.store'), [
'title' => 'Plan the week',
])->assertRedirect(route('tasks.index'));
$this->assertDatabaseHas('tasks', [
'title' => 'Plan the week',
]);
}
public function test_a_task_requires_a_title(): void
{
$this->from(route('tasks.index'))
->post(route('tasks.store'), [
'title' => '',
])
->assertRedirect(route('tasks.index'))
->assertSessionHasErrors('title');
$this->assertDatabaseCount('tasks', 0);
}
}
Run the test suite:
php artisan test
The RefreshDatabase trait resets the test database between runs so leftover rows from one test do not affect the next. Make sure you configure a separate test database connection so the test suite never touches production data. Laravel covers this in its guide to feature tests and database testing.
Right now, everyone who visits the app shares a single task list. If you want each person to have a private list, add a user_id foreign key to the tasks table to link every task to its owner. Then query tasks through the signed-in user, and verify that the user owns a task before letting them edit or delete it. Without that ownership check, someone could change the task ID in a URL and modify another person’s task.
If you need user accounts and login, Laravel’s starter kits provide that code out of the box. Because a starter kit adds extra setup beyond the task features, it makes more sense to install one when login is part of your first version than to bolt it on later. You can browse the available options on Laravel’s starter kits page.
Give Vroni a GitHub issue, bug report, spec, or rough idea. It reads the repo, plans the change, writes code, runs checks, and works toward a review-ready pull request.
Take a look at vroni.com