Get 20% off web development packages
5 Powerful Laravel Tricks to Write Better Code and Improve Performance
If you work with Laravel regularly, you probably already know that the framework's strength is not only in its major features. A lot of its power comes from small features and techniques that can significantly reduce code, improve readability, and increase application performance.
In this article, we will explore 5 practical Laravel tricks that are especially useful when working with Eloquent, database queries, relationships, and application performance.
The goal is not simply to memorize Laravel methods, but to understand when and why you should use them.
1. Use Route Model Binding Instead of Manually Finding Models
One of the easiest ways to keep Laravel controllers clean is using Route Model Binding.
Instead of manually receiving an ID and querying the model:
public function show($id)
{
$project = Project::findOrFail($id);
return view('projects.show', compact('project'));
}
You can let Laravel resolve the model automatically:
public function show(Project $project)
{
return view('projects.show', compact('project'));
}
With the following route:
Route::get('/projects/{project}', [ProjectController::class, 'show']);
Laravel understands that {project} should be resolved using the Project model.
If the model cannot be found, Laravel automatically handles the request with a 404 response.
Why is Route Model Binding useful?
It:
- Reduces repetitive code.
- Keeps controllers cleaner.
- Eliminates unnecessary
findOrFail()calls. - Makes routes and controllers easier to understand.
- Uses Laravel's built-in functionality instead of repeating common logic.
You can also customize the route key and use a slug instead of an ID, which is especially useful for SEO-friendly websites.
2. Use Eager Loading to Avoid the N+1 Query Problem
This is one of the most important performance concepts every Laravel developer should understand.
Imagine that you have a collection of projects and each project belongs to a client:
$projects = Project::all();
foreach ($projects as $project) {
echo $project->client->name;
}
The code looks perfectly normal, but it can generate a large number of database queries.
Laravel first retrieves the projects, and then additional queries may be executed when accessing each client's data.
This is known as the N+1 Query Problem.
The solution is Eager Loading:
$projects = Project::with('client')->get();
If you need multiple relationships:
$projects = Project::with([
'client',
'category',
'services',
'images',
])->get();
This tells Laravel to load the required relationships in advance, which can dramatically reduce the number of database queries.
A practical example
For a projects page:
$projects = Project::with([
'category',
'client',
'images',
])
->latest()
->paginate(12);
This is much more efficient than loading projects first and allowing every relationship to be queried separately while rendering the page.
An important note
Do not automatically eager load every relationship on your model.
Only load the relationships you actually need for the current page. Loading unnecessary relationships can increase memory usage and response size.
3. Use when() to Build Clean Conditional Queries
Search and filtering pages often contain code like this:
$query = Project::query();
if ($request->category) {
$query->where('category_id', $request->category);
}
if ($request->status) {
$query->where('status', $request->status);
}
$projects = $query->get();
This works, but it can become difficult to maintain when the number of filters grows.
Laravel's when() method provides a cleaner approach:
$projects = Project::query()
->when($request->category, fn ($query, $category) =>
$query->where('category_id', $category)
)
->when($request->status, fn ($query, $status) =>
$query->where('status', $status)
)
->get();
It is particularly useful for search functionality:
$projects = Project::query()
->when($request->search, fn ($query, $search) =>
$query->where('title', 'like', "%{$search}%")
)
->latest()
->paginate(20);
The search condition is only applied when the search value exists.
Why use when()?
It makes Query Builder code cleaner and more flexible, especially in:
- Search pages.
- Filter systems.
- Admin dashboards.
- Reporting systems.
- APIs.
- ERP applications.
- E-commerce platforms.
4. Use Query Scopes to Organize Business Logic
If the same query appears in multiple places, there is no reason to keep writing it.
For example:
Project::where('status', 'active')->get();
If this condition is used throughout the application, create a Local Scope inside the model:
public function scopeActive($query)
{
return $query->where('status', 'active');
}
Now you can simply write:
$projects = Project::active()->get();
You can create additional scopes:
public function scopePublished($query)
{
return $query->where('published', true);
}
And combine them:
$projects = Project::active()
->published()
->latest()
->get();
This makes the model more expressive and keeps business rules reusable.
For example:
public function scopeFeatured($query)
{
return $query->where('is_featured', true);
}
Then:
$projects = Project::active()
->published()
->featured()
->latest()
->take(6)
->get();
This becomes particularly valuable as the application grows.
5. Use Cache for Data That Does Not Change Frequently
The final trick, and one of the most powerful performance improvements, is using Cache properly.
Suppose your homepage displays a list of services:
$services = Service::active()->get();
If the page receives thousands of visits, there is no reason to execute the same database query on every request when the data changes only occasionally.
You can use:
$services = Cache::remember(
'services',
now()->addHours(6),
fn () => Service::active()->get()
);
The first request executes the query and stores the result in the cache.
Subsequent requests can retrieve the data from the cache instead of querying the database again.
A more realistic example
For the latest projects on the homepage:
$projects = Cache::remember(
'homepage.projects',
now()->addHour(),
fn () => Project::with([
'category',
'images',
])
->active()
->latest()
->take(6)
->get()
);
Here, we are combining several techniques:
- Eager Loading
- Query Scopes
- Sorting
- Limiting
- Caching
This is the type of approach that can make a Laravel application faster and more maintainable.
When Should You Clear the Cache?When the underlying data changes, you should make sure the related cache is refreshed.
For example:
Cache::forget('services');
The next request will execute the query again and store the updated result.
In larger applications, it is often better to manage cache invalidation through Events, Observers, or dedicated Services rather than scattering Cache::forget() calls throughout the codebase.
This is an important point.
If you have an inefficient query such as:
Project::where('title', 'like', '%laravel%')->get();
do not assume that adding Cache is the complete solution.
Ask yourself first:
Is the query itself optimized?
Do you have the correct indexes?
Should you use pagination?
Do you need every column?
Do you need every result?
Are you experiencing an N+1 problem?
Are relationships being loaded correctly?
Cache is powerful, but it should not replace good database and query design.
ConclusionLaravel provides a large collection of tools that allow developers to write less code while keeping applications clean, maintainable, and efficient.
The five Laravel tricks covered in this article are:
- Route Model Binding to reduce repetitive controller code.
- Eager Loading to avoid N+1 queries.
- when() to build dynamic queries cleanly.
- Query Scopes to organize reusable business logic.
- Cache to reduce database load and improve application performance.
The most important part is not simply knowing these features, but understanding when to use each one.
In real-world Laravel applications, performance rarely comes from a single trick. It usually comes from many small, correct decisions across the database, Eloquent, caching, and application architecture.
If you are working on a Laravel project today, start by reviewing your existing queries and look specifically for N+1 queries, repeated database operations, and data that can safely be cached.
Article Category
5 Powerful Laravel Tricks to Write Better Code and Improve Performance
Discover 5 practical Laravel tricks that can help you write cleaner and more efficient code. Learn how to use Route Model Binding, Eager Loading, conditional queries with when(), Query Scopes, and Cache to improve Laravel application performance and maintainability.
Consultation & Communication
Direct communication via WhatsApp or phone to understand your project needs precisely.
Planning & Scheduling
Creating clear work plan with specific timeline for each project phase.
Development & Coding
Building projects with latest technologies ensuring high performance and security.
Testing & Delivery
Comprehensive testing and thorough review before final project delivery.
Specializations Related to This Article
All ServicesServices Related to This Article
All ServicesWant to apply this article to your project?
If this topic is relevant to your current project, you can jump to one of the services above or browse the services page to choose the most suitable solution.