Laravel is famous for its elegant syntax and powerful, well-known features like Eloquent ORM, Blade templating, and the robust Artisan console. But beneath its popular surface lies a treasure trove of lesser-known tools that can dramatically improve your code’s expressiveness and efficiency.
These hidden gems can help you solve complex problems with surprising simplicity, making your development process smoother and your applications more maintainable. Let’s move beyond the make:model and make:controller routine and explore five powerful Laravel features you might have never tried.
1. Macros: Add Your Own Methods to Framework Classes
What it is: Have you ever wished a core Laravel class, like Collection or Response, had a custom method just for your application? With Macros, you can do exactly that. They allow you to add custom methods to framework classes at runtime.
Why it’s powerful: Macros let you extend Laravel’s functionality without messy inheritance or wrapping classes. You can create application-specific utilities that feel native to the framework, keeping your code incredibly clean and expressive.
How to use it:
Typically, you’d define a Macro in a service provider’s boot method.
// In AppServiceProvider.php
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
public function boot()
{
// Add a 'toUpper' macro to all Collections
Collection::macro('toUpper', function () {
return $this->map(function ($value) {
return Str::upper($value);
});
});
// Usage in your code:
$names = collect(['alice', 'bob', 'charlie']);
$shoutingNames = $names->toUpper(); // ['ALICE', 'BOB', 'CHARLIE']
}
2. The Higher Order “Tap” Method
What it is: The tap() function is a utility that allows you to "tap" into a fluent chain, perform an action on the passed value, and then return the value itself. It's perfect for performing side operations without breaking your method chain.
Why it’s powerful: It eliminates the need for temporary variables mid-chain, making your code more fluent and functional. It’s incredibly useful for debugging or performing actions like logging within a complex chain of operations.
How to use it:
Imagine creating a new user and logging the event without breaking your flow.
// Without tap (requires a temporary variable)
$user = new User(['name' => 'John Doe']);
$user->save();
Log::info('New user created: ' . $user->id);
return $user;
// With the elegant tap()
return tap(new User(['name' => 'John Doe']), function ($user) {
$user->save();
Log::info('New user created: ' . $user->id);
});
// The $user object is automatically returned after the closure runs.
3. The “Once” Helper Function
What it is: A deceptively simple global helper function once() that ensures a given piece of code runs one time and one time only, no matter how many times it's called in a request lifecycle.
Why it’s powerful: It’s perfect for preventing expensive, side-effect operations from running multiple times by accident. Think of things like logging a specific event, updating a metrics counter, or loading a heavy configuration file.
How to use it:
Wrap the code you want to protect inside the once closure.
public function handle($request, $next)
{
$response = $next($request);
// This log will only be written once, even if this method is called multiple times
once(function () use ($response) {
Log::info('Response was sent for URL: ' . $request->url());
});
return $response;
}
4. The “Number” Helper Utility (Laravel 10+)
What it is: Introduced in Laravel 10, the Number helper is a simple but incredibly useful class for formatting numbers according to locale-specific rules.
Why it’s powerful: If your application has an international audience, formatting currency, percentages, or file sizes correctly is crucial. This helper abstracts away the complexity of PHP’s NumberFormatter into a clean, fluent API.
How to use it:
Format numbers for different contexts with ease.
use Illuminate\Support\Number;
// Format currency
Number::currency(4999.99, 'USD'); // '$4,999.99'
Number::currency(4999.99, 'EUR'); // '€4.999,99'
// Format percentages
Number::percentage(75.67); // '76%'
Number::percentage(75.67, 1); // '75.7%'
// Human-readable file sizes
Number::fileSize(1024 * 1024); // '1 MB'
Number::fileSize(1024 * 1024 * 5.4, 1); // '5.4 MB'
5. The Conditionable Trait
What it is: This is the magic behind those beautiful ->when() and ->unless() chains you see on Eloquent queries and Collections. The best part? You can easily add this trait to your own classes to make them conditionally fluent!
Why it’s powerful: It makes conditional logic in your method chains readable and declarative. Instead of breaking your chain with an if statement, you can keep it flowing smoothly.
How to use it in your own class:
Just use the Conditionable trait.
use Illuminate\Support\Traits\Conditionable;
class ProcessJob
{
use Conditionable;
public function sendEmail($user) { ... /* returns $this */ }
public function generateReport($user) { ... /* returns $this */ }
public function logActivity($user) { ... /* returns $this */ }
}
// Now you can write incredibly expressive conditional chains:
$job = new ProcessJob;
$job->generateReport($user)
->when($user->wantsEmail, fn($job) => $job->sendEmail($user))
->unless($user->isAdmin, fn($job) => $job->logActivity($user));
Conclusion
Laravel’s depth is one of its greatest strengths. While its core features get the job done brilliantly, exploring these hidden corners of the framework can elevate your code from functional to exceptional.
The next time you find yourself writing a complex workaround, take a moment to dig through the Laravel documentation. You might just find a built-in, elegant solution waiting for you. What’s your favorite underrated Laravel feature? Share it with other developers to help everyone write better code.
If you found this helpful, feel free to share or drop a comment. Happy coding with Laravel! 🧱✨
Free resources for this topic
Code snippets and fixes for this topic
Get one practical tip every week
New tutorials, fixes and free cheat sheets from DEV Talk, straight to your inbox. No spam, unsubscribe in one click.
Free download: Laravel interview questions (PDF)
Have a question about this post?
Ask the community: other developers and the author can answer.
Get notified about new articles
One click, no email needed. Turn it off anytime with the bell at the top.
Get new articles on your iPhone
Add DEV Talk to your Home Screen, open it, then tap the bell.
Enjoying the content?
If this article helped you, you can support the author with a coffee. It keeps new posts coming.
Comments 0
No comments yet
Be the first to share your thoughts.