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();
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);
This helps with versioning, security, and response clarity.
Use Laravel's Str
helper
Str::slug('Post Title') // returns: post-title
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();
});
Clean syntax, easy to write and maintain.
Bonus: Use php artisan model:show User
to view relationships right in your terminal.
Top comments (0)