DEV Community

Aleson França
Aleson França

Posted on

Laravel Tips: For Beginners

Working with Laravel is great, but we can always improve how we use the framework. Here are 5 quick tips to help you write better code:

Use when() instead of if in Eloquent

User::query()
    ->when($isActive, fn($q) => $q->where('active', true))
    ->get();
Enter fullscreen mode Exit fullscreen mode

This avoids external if statements and makes the query cleaner.


Use Resources to format API responses

Avoid return $user directly. Instead, use:

return new UserResource($user);
Enter fullscreen mode Exit fullscreen mode

This helps with versioning, security, and response clarity.


Use Laravel's Str helper

Str::slug('Post Title') // returns: post-title
Enter fullscreen mode Exit fullscreen mode

Simple, powerful, and more readable.


Don't put heavy logic in Controller

Use Services, Actions, to keep your controllers clean and easy to read.


Write tests with Pest

it('creates a user', function () {
    $response = post('/users', [...]);

    $response->assertCreated();
});
Enter fullscreen mode Exit fullscreen mode

Clean syntax, easy to write and maintain.


Bonus: Use php artisan model:show User to view relationships right in your terminal.

Top comments (0)