Jose Jimenez
Jose Jimenez
Software Architect & Developer
> >

Laravel Quick Tips: Simplify Your Eloquent Queries

Published in Laravel, Database on Sep 29, 2023

In this blog post, I will share two quick tips that will help you simplify your Laravel Eloquent queries. These tips will not only improve the readability of your code but also enhance the efficiency of your application. Let's dive in!

Tip 1: Eloquent use query() method

When using Laravel Eloquent, you can add the query() method after the model to make your code more concise and readable. This method not only returns the query builder for Eloquent models but also allows you to chain multiple query operations seamlessly.

Here's an example of how you can implement this tip:

1$users = App\Models\User::query()
2 ->where('is_approved', true)
3 ->whereNotNull('email_verified_at')
4 ->get();

By using the query() method, you can clearly define your query conditions, making it easier for developers to understand the intent of the code. This tip can improve code maintainability and facilitate future modifications.

Tip 2: Eloquent and DB facade, use when()

The when() method comes in handy when you want to conditionally run a query based on certain criteria. By utilizing the power of Laravel's environment detection and conditional clauses, you can construct dynamic queries effortlessly.

Let's take an example where we only want to return approved users in the production environment:

1$users = App\Models\User::query()
2 ->when(App::environment('production'), function ($query) {
3 $query->where('is_approved', true);
4 })
5 ->whereNotNull('email_verified_at')
6 ->get();

In this example, the when() method checks if the application environment is set to "production." If it is, the closure function is executed, which adds an additional condition to the query. This allows you to control the query behavior dynamically without cluttering your code with if-else statements.


By implementing these two quick tips, you can simplify your Laravel Eloquent queries and improve the readability of your codebase. The use of query() method enhances code clarity, while the when() method adds flexibility to your conditional queries. Apply these tips in your projects and witness the benefits firsthand. Happy coding with Laravel!