DEV Community

Cover image for Laravel Eloquent Tips & Tricks Every Pro Developer Should Know
Engineer Robin 🎭
Engineer Robin 🎭

Posted on

Laravel Eloquent Tips & Tricks Every Pro Developer Should Know

Laravel Eloquent is one of the most powerful and expressive ORM systems in the PHP ecosystem. However, most developers only scratch the surface of what Eloquent can truly do.

This article covers advanced Laravel Eloquent tips and best practices that professional developers use to write cleaner, faster, and more scalable applications.


1. Avoid the N+1 Query Problem

One of the most common performance issues in Laravel applications is the N+1 query problem.

Bad Practice

$posts = Post::all();
foreach ($posts as $post) {
    echo $post->user->name;
}
Enter fullscreen mode Exit fullscreen mode

This results in multiple database queries.

Best Practice

$posts = Post::with('user')->get();
Enter fullscreen mode Exit fullscreen mode

Eager loading drastically reduces the number of database queries and improves performance.


2. Select Only Required Columns

Fetching unnecessary columns increases memory usage and slows down queries.

Bad Practice

User::all();
Enter fullscreen mode Exit fullscreen mode

Best Practice

User::select('id', 'name', 'email')->get();
Enter fullscreen mode Exit fullscreen mode

Always fetch only the data you actually need.


3. Process Large Data Using Chunking

Loading large datasets at once can crash your application.

Best Practice

User::chunk(100, function ($users) {
    foreach ($users as $user) {
        // process user
    }
});
Enter fullscreen mode Exit fullscreen mode

Chunking keeps memory usage low and is ideal for background jobs and cron tasks.


4. Use Advanced Relationships

Professional applications often require complex relationships such as:

  • hasOneThrough
  • hasManyThrough
  • polymorphic relationships

Example:

public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}
Enter fullscreen mode Exit fullscreen mode

These relationships help keep database design clean and scalable.


5. Use Query Scopes for Clean Code

Instead of repeating conditions, use query scopes.

User::active()->admin()->get();
Enter fullscreen mode Exit fullscreen mode
public function scopeActive($query)
{
    return $query->where('status', 'active');
}
Enter fullscreen mode Exit fullscreen mode

Scopes make queries readable and reusable.


6. Protect Against Mass Assignment

Never trust user input blindly.

Bad Practice

User::create($request->all());
Enter fullscreen mode Exit fullscreen mode

Best Practice

protected $fillable = ['name', 'email'];
Enter fullscreen mode Exit fullscreen mode

or

protected $guarded = ['is_admin'];
Enter fullscreen mode Exit fullscreen mode

This prevents unauthorized data modification.


7. Use exists() Instead of count()

Bad Practice

User::where('email', $email)->count();
Enter fullscreen mode Exit fullscreen mode

Best Practice

User::where('email', $email)->exists();
Enter fullscreen mode Exit fullscreen mode

exists() stops the query as soon as a match is found, making it faster.


8. Use withCount() for Relationship Counts

Bad Practice

$post->comments->count();
Enter fullscreen mode Exit fullscreen mode

Best Practice

Post::withCount('comments')->get();
Enter fullscreen mode Exit fullscreen mode

This avoids loading entire relationships unnecessarily.


9. Update Records Without Fetching Them

Bad Practice

$user = User::find($id);
$user->status = 'active';
$user->save();
Enter fullscreen mode Exit fullscreen mode

Best Practice

User::where('id', $id)->update(['status' => 'active']);
Enter fullscreen mode Exit fullscreen mode

This reduces database queries.


10. Use firstOrCreate and updateOrCreate

User::firstOrCreate(
    ['email' => $email],
    ['name' => $name]
);
Enter fullscreen mode Exit fullscreen mode

These methods simplify logic and prevent race conditions.


11. Use Attribute Casting

protected $casts = [
    'is_active' => 'boolean',
    'settings' => 'array',
    'email_verified_at' => 'datetime',
];
Enter fullscreen mode Exit fullscreen mode

Casting ensures consistent data types across your application.


12. Hide Sensitive Fields in Responses

protected $hidden = [
    'password',
    'remember_token',
];
Enter fullscreen mode Exit fullscreen mode

This is essential for API security.


13. Use Database Transactions

DB::transaction(function () {
    Order::create([...]);
    Payment::create([...]);
});
Enter fullscreen mode Exit fullscreen mode

Transactions prevent partial data corruption in critical operations.


14. Avoid Overusing DB::raw()

Raw queries reduce readability and increase security risks.
Use Eloquent wherever possible.


15. Monitor and Optimize Queries

DB::listen(function ($query) {
    logger($query->sql);
});
Enter fullscreen mode Exit fullscreen mode

Regular query monitoring helps identify performance bottlenecks early.


Top comments (0)