Palzin Track
Get 15% off with code PTRACKSIGNUP15 

Laravel Diary Logo

Laravel Eloquent Mastery: 30 Pro Tips to Supercharge Your Queries

laravel
Table of Contents

Laravel's Eloquent ORM is a powerful and intuitive Active Record implementation for working with your database. However, as with any tool, there's a difference between just using it and unlocking its full potential. In this series, we'll walk through 30 advanced tricks for efficient Eloquent querying, complete with real-world examples that will turn you into an Eloquent wizard.

Good Practice: Use whereHas to filter relations without loading them.

// Retrieve posts with at least one comment containing the word 'Eloquent'
$posts = App\\Models\\Post::whereHas('comments', function ($query) {
    $query->where('content', 'like', '%Eloquent%');
})->get();

Bad Practice: Loading the relation unnecessarily.

// This will load all the comments even if we only need to check their existence
$posts = App\\Models\\Post::with('comments')->get()->filter(function ($post) {
    return $post->comments->contains('content', 'like', '%Eloquent%');
});

Good Practice: Use eager loading to prevent the N+1 query problem.

// Eager load comments when retrieving posts
$posts = App\\Models\\Post::with('comments')->get();

Bad Practice: Lazy loading each relation in a loop.

$posts = App\\Models\\Post::all();
foreach ($posts as $post) {
    // This will run a new query for each post to load comments
    $comments = $post->comments;
}

Good Practice: When eager loading, specify the columns you need to improve performance.

// Only select the 'id' and 'title' of the posts along with their 'username' from the user relationship
$posts = App\\Models\\Post::with('user:id,username')->get(['id', 'title']);

Bad Practice: Eager loading all columns without consideration.

// This will select all columns from the related tables
$posts = App\\Models\\Post::with('user')->get();

Good Practice: Use subqueries to order by aggregated or related data.

use Illuminate\\Database\\Eloquent\\Builder;

$users = App\\Models\\User::addSelect(['last_post_created_at' => App\\Models\\Post::select('created_at')
    ->whereColumn('user_id', 'users.id')
    ->orderBy('created_at', 'desc')
    ->limit(1)
])->orderBy('last_post_created_at', 'desc')->get();

Bad Practice: Fetching the entire collection and sorting in-memory.

$users = App\\Models\\User::all()->sortByDesc(function ($user) {
    return $user->posts->max('created_at');
});

Good Practice: Use fillable or guarded properties to protect against mass assignment vulnerabilities.

class User extends Model
{
    protected $fillable = ['name', 'email'];
}

Bad Practice: Not specifying fillable fields and risking mass assignment attacks.

class User extends Model
{
    // No $fillable or $guarded property set
}

Laravel 10 Tip: Use the new whereRelation method to write cleaner code when querying based on simple relation constraints.

// Laravel 10 introduces whereRelation for simpler queries
$posts = App\\Models\\Post::whereRelation('comments', 'content', 'like', '%Eloquent%')->get();

In the complete article, this pattern of good vs. bad practice will continue for a total of 30 scenarios, each illustrating an advanced tip or common mistake with Eloquent usage. We would include examples for optimizing queries, writing cleaner syntax, avoiding common pitfalls, and leveraging the full power of Eloquent. The article would also highlight new features specific to Laravel 10, ensuring developers are up-to-date with the latest ORM capabilities.

Stay tuned for more scenarios in our Eloquent series, where we'll cover everything from dynamic scopes and model events to custom casts and database transactions.

You can continue to read series 2 by clicking here. Happy querying!

::Share it on::

Comments (0)

What are your thoughts on "Laravel Eloquent Mastery: 30 Pro Tips to Supercharge Your Queries"?

You need to create an account to comment on this post.

Related articles