Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 67 ยท Practice and Review

Practice Exercises with Solutions

Twelve Laravel exercises on routing, validation, Eloquent, authorization, queues, caching and testing, each with a worked solution and runnable stand-ins.

Reading about a framework is not the same as using it. These twelve exercises cover the everyday skills of a Laravel developer: routing, validation, Eloquent, eager loading, policies, queues, middleware, API resources, testing, events, caching and code review. Each exercise has a short brief, then a solution you can compare with your own.

Try every exercise in a real Laravel app first (a fresh laravel new project with SQLite is enough). Cover the solution, write your version, run it, and only then read on. If your answer differs from the solution, that is fine: ask whether yours is correct, readable and safe.

Laravel cannot run on this site, so the real Laravel solutions are read-only code blocks. Where it helps, a runnable plain-PHP stand-in shows the same idea so you can experiment with it, and the text says which is which. The stand-ins are not Laravel's code.

flowchart LR
    R["Routing<br/>1"] --> M["Middleware<br/>7"]
    M --> V["Validation<br/>2"]
    V --> A["Authorization<br/>5"]
    A --> E["Eloquent<br/>3, 4, 12"]
    E --> Q["Queues and events<br/>6, 10"]
    E --> C["Caching<br/>11"]
    E --> J["API resources<br/>8"]
    T["Testing<br/>9"] -.-> R

Where each exercise sits in a request. Testing (9) covers the whole path.

Exercise 1: routes with constraints and names

Task. Define a route GET /posts/{post} named posts.show that only accepts numeric IDs (anything else should give a 404, not an error page), and a route GET /archive/{year?} named archive where the optional year must be four digits. Generate the URL for the first route from its name.

Solution (Laravel, read-only).

PHP
Route::get('/posts/{post}', [PostController::class, 'show'])
    ->whereNumber('post')
    ->name('posts.show');

Route::get('/archive/{year?}', [ArchiveController::class, 'index'])
    ->where('year', '[0-9]{4}')
    ->name('archive');

$url = route('posts.show', ['post' => 42]);   // https://your-app.test/posts/42

Constraints turn bad input into a clean 404 before your controller runs, and route() means a URL change in one place updates every link. See routing basics.

Here is a stand-in that compiles patterns with constraints, dispatches paths and generates URLs by name:

PHP Exercise 1: a tiny router with constraints

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.

Exercise 2: validate a registration

Task. Validate a registration form: name required (max 80 characters), email required, valid and unique in users, password at least 8 characters and confirmed, role one of student or teacher. Use a form request, and make role an enum rule.

Solution (Laravel, read-only).

PHP
class RegisterRequest extends FormRequest
{
    /** @return array<string, array<int, mixed>> */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:80'],
            'email' => ['required', 'email', 'max:255', Rule::unique('users', 'email')],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
            'role' => ['required', Rule::enum(Role::class)],
        ];
    }
}

The controller then uses $request->validated(), which contains only the fields you validated, never extra input an attacker added. More in form requests and custom rules.

The stand-in below implements required, email, min, confirmed and in rules and prints the errors, so you can see how rule strings are interpreted:

PHP Exercise 2: a rule-based validator

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.

Exercise 3: a scope and a count

Task. A Post has many Comments. Write a local scope published() (rows with a published_at in the past) and list published posts with their comment counts in one query.

Solution (Laravel, read-only).

PHP
class Post extends Model
{
    public function scopePublished(Builder $query): void
    {
        $query->whereNotNull('published_at')->where('published_at', '<=', now());
    }

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}

$posts = Post::published()->withCount('comments')->latest('published_at')->get();

foreach ($posts as $post) {
    echo "{$post->title}: {$post->comments_count}";
}

withCount() adds a subquery, so the counts arrive with the posts in a single query instead of one count query per post. The stand-in runs the equivalent SQL on SQLite with a fixed "now", so you can read the query that Eloquent builds for you. See querying with Eloquent.

PHP Exercise 3: the SQL behind a scope and withCount

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.

Exercise 4: remove an N+1 query

Task. This view shows each post's author name and runs 1 + N queries. Fix it, and make the app complain loudly if someone introduces a lazy load again.

PHP
$posts = Post::latest()->take(20)->get();

foreach ($posts as $post) {
    echo $post->author->name;
}

Solution (Laravel, read-only).

PHP
$posts = Post::with('author:id,name')->latest()->take(20)->get();

// AppServiceProvider::boot()
Model::preventLazyLoading(! app()->isProduction());

with('author:id,name') loads all authors in one extra query and only the columns you need. preventLazyLoading() throws an exception in development whenever code lazy loads a relationship, so the bug is caught before it ships; leaving it off in production means a missed spot slows a page rather than breaking it. See eager loading and N+1.

Exercise 5: a policy with an admin override

Task. Authors may update their own posts. They may delete them only while no comments exist. Admins may do everything. Write the policy.

Solution (Laravel, read-only).

PHP
class PostPolicy
{
    public function before(User $user, string $ability): ?bool
    {
        return $user->is_admin ? true : null;
    }

    public function update(User $user, Post $post): bool
    {
        return $user->id === $post->user_id;
    }

    public function delete(User $user, Post $post): bool
    {
        return $user->id === $post->user_id && $post->comments()->doesntExist();
    }
}

before() runs first: returning true allows, and null means "carry on with the normal checks". Note that before returns null, not false, for non-admins; returning false would block everyone else, including owners. In a controller you call $this->authorize('update', $post), and in Blade @can('update', $post). See gates and policies.

PHP Exercise 5: a policy engine with a before hook

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.

Exercise 6: an idempotent queued job

Task. Write a SendWelcomeEmail job that sends the welcome mail once per user, even if the job runs twice (a retry, a duplicate dispatch).

Solution (Laravel, read-only).

PHP
class SendWelcomeEmail implements ShouldQueue
{
    use Queueable;

    public int $tries = 3;

    public function __construct(public int $userId)
    {
    }

    public function handle(): void
    {
        $sent = User::whereKey($this->userId)
            ->whereNull('welcome_sent_at')
            ->update(['welcome_sent_at' => now()]);

        if ($sent === 0) {
            return;
        }

        Mail::to(User::find($this->userId))->send(new WelcomeMail());
    }
}

The conditional update is both the check and the claim, and it is atomic: only one run can flip welcome_sent_at from null, and update() returns the number of changed rows. A second run changes zero rows and exits. (The trade-off: if the mail fails after the claim, you would need to undo the claim in a failed() method. Choose the order that matches the damage of a lost mail against a double mail.) Background in queues and jobs.

PHP Exercise 6: running a job twice

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.

Exercise 7: admin-only middleware

Task. Create a middleware alias admin that returns 403 for users who are not admins, and apply it to a group of routes under /admin.

Solution (Laravel, read-only).

PHP
// php artisan make:middleware EnsureUserIsAdmin
class EnsureUserIsAdmin
{
    public function handle(Request $request, Closure $next): Response
    {
        abort_unless($request->user()?->is_admin, 403);

        return $next($request);
    }
}

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias(['admin' => EnsureUserIsAdmin::class]);
})

// routes/web.php
Route::middleware(['auth', 'admin'])->prefix('admin')->name('admin.')->group(function () {
    Route::get('/', [AdminController::class, 'index'])->name('index');
});

Order matters: auth runs first, so guests go to the login page instead of getting a 403. The null-safe ?-> covers the case where no user exists at all. See middleware.

Exercise 8: an API resource

Task. Return a post as JSON with its id, title, the author's name (only if the author was loaded) and the comment count (only if counted). The author's email must never appear.

Solution (Laravel, read-only).

PHP
class PostResource extends JsonResource
{
    /** @return array<string, mixed> */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'author' => $this->whenLoaded('author', fn () => ['name' => $this->author->name]),
            'comments_count' => $this->whenCounted('comments'),
        ];
    }
}

return PostResource::collection(
    Post::published()->with('author:id,name')->withCount('comments')->paginate(15)
);

whenLoaded() and whenCounted() drop the key entirely when the data was not loaded, which avoids both missing-relation errors and accidental lazy loading inside the resource. Because the resource lists fields by name, the email cannot leak. See API resources.

Exercise 9: write the tests

Task. Write Pest tests for exercises 1 and 2: a non-numeric post ID is a 404, and an invalid registration shows errors and creates no user.

Solution (Laravel, read-only).

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

it('returns 404 for a non-numeric post id', function () {
    $this->get('/posts/abc')->assertNotFound();
});

it('shows a post by numeric id', function () {
    $post = Post::factory()->create();

    $this->get("/posts/{$post->id}")->assertOk()->assertSee($post->title);
});

it('rejects an invalid registration', function () {
    $this->post('/register', [
        'name' => '',
        'email' => 'not-an-email',
        'password' => 'short',
        'password_confirmation' => 'other',
        'role' => 'owner',
    ])->assertSessionHasErrors(['name', 'email', 'password', 'role']);

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

Test the happy path and the important failure. The last line is easy to forget and checks the thing that actually matters: nothing was saved. See HTTP and database tests.

Exercise 10: react once when a post is published

Task. When a post's published_at changes from null to a date, dispatch a PostPublished event exactly once. Editing an already published post must not fire it again.

Solution (Laravel, read-only).

PHP
class Post extends Model
{
    protected static function booted(): void
    {
        static::updated(function (Post $post) {
            if ($post->wasChanged('published_at') && $post->getOriginal('published_at') === null) {
                PostPublished::dispatch($post);
            }
        });
    }
}

Inside the updated hook, wasChanged() tells you what this save changed and getOriginal() still holds the old value. Listeners for PostPublished (notify followers, ping a search index) can be queued, and should be dispatched after the transaction commits if the update happens inside one. See model events and events and listeners.

Exercise 11: cache the front page

Task. Cache the five latest published posts for ten minutes, and refresh the cache as soon as any post is saved or deleted.

Solution (Laravel, read-only).

PHP
class HomeController extends Controller
{
    public function __invoke(): View
    {
        $posts = Cache::remember('home:latest-posts', 600, function () {
            return Post::published()->latest('published_at')->take(5)->get(['id', 'title', 'slug', 'published_at']);
        });

        return view('home', ['posts' => $posts]);
    }
}

// in the Post model
protected static function booted(): void
{
    static::saved(fn () => Cache::forget('home:latest-posts'));
    static::deleted(fn () => Cache::forget('home:latest-posts'));
}

The TTL is a safety net and the forget calls are the actual invalidation: users see changes at once, while a busy site still serves almost every request from the cache. The cache key lives in two places, so put it in a constant. Caching only the columns you display keeps the entry small. See caching.

Exercise 12: review this controller

Task. List everything wrong with this code.

PHP
public function store(Request $request)
{
    $post = Post::create($request->all());

    $term = $request->query('q');
    $rows = DB::select("select * from posts where title like '%$term%'");

    foreach (Post::all() as $p) {
        echo $p->author->name;
    }

    if (env('APP_DEBUG')) {
        logger($request->all());
    }

    return redirect('/posts/' . $post->id);
}

Solution. Seven problems:

  1. No validation. Any input is accepted; use a form request and $request->validated().
  2. Mass assignment. $request->all() lets a client set any fillable (or, with $guarded = [], every) column, such as user_id or is_featured. Pass only validated fields and set the owner from $request->user().
  3. SQL injection. $term is concatenated into the SQL. Use bindings: DB::select('select * from posts where title like ?', ["%{$term}%"]), or the query builder.
  4. N+1 and unbounded loading. Post::all() loads the whole table, and $p->author queries once per row. Paginate and use with('author').
  5. env() outside config files. After config:cache, env() returns null in application code. Read config('app.debug').
  6. Output and logging problems. echo inside a controller bypasses views and escaping, and logger($request->all()) may write passwords and tokens to the logs.
  7. No authorization, hard-coded URL. Check a policy before creating, and use redirect()->route('posts.show', $post).

Seeing these as a list is the point: most real bugs are one of these familiar shapes. More in security in Laravel.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a policy, what should before() return for a regular (non-admin) user to let the normal checks continue?

    Returning true allows, false denies everything, and null means no opinion, so the specific policy method decides.
  2. 2. Why is a conditional update (WHERE welcome_sent_at IS NULL) a good way to make a job idempotent?

    Two runs cannot both change the row from null. The number of affected rows tells each run whether it won.
  3. 3. Why is env('APP_DEBUG') in application code a bug?

    Read environment values in config files and access them with config() everywhere else.
  4. 4. What does Post::with('author:id,name') achieve?

    Eager loading replaces N queries with one, and the column list keeps the data small. Include the key column (id) so Eloquent can match authors to posts.
  5. 5. Which is the best way to build the cache invalidation for the front page?

    Forgetting the key on writes makes changes visible immediately, while the TTL guarantees that stale data eventually disappears.

Summary

  • Constrain route parameters, name routes, and generate URLs with route().
  • Validate in form requests and use only validated() data; never trust $request->all().
  • Use scopes, withCount() and with() to keep queries few; turn on preventLazyLoading() in development.
  • Policies hold authorization rules; before() returns true or null, not false, for non-admins.
  • Make queued jobs idempotent with an atomic conditional update.
  • Test the happy path and the failure that matters, including "nothing was saved".
  • Cache with a TTL plus explicit invalidation, and never call env() outside config files.

Next: Laravel Interview Questions