One of the many magic features of Laravel is the ability to add custom methods to many classes of the framework.
These custom methods are called macros, and you define them at runtime.
You can add macros to any class that uses the Macroable
trait
.
Macros can be a clean way to solve specific problems.
For example, imagine that your project needs to regularly check if a request is made by a human or by a robot.
You can define a macro on the Request
class in the boot
method of your AppServiceProvider
:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
\Illuminate\Http\Request::macro('isRobot', function () {
return Str::contains(
strtolower($this->userAgent()),
['bot', 'crawl', 'slurp', 'spider', 'facebook', 'mediapartners', 'ohdear']
);
});
}
}
Now, in your controllers, you can use your new isRobot()
macro directly on the Request
class:
public function show(Request $request, BlogPost $blogPost)
{
if (! $request->isRobot()) {
$blogPost->incrementPageViews();
}
return view('blog', ['blogPost' => $blogPost]);
}
Pretty clean!
Because macros are defined at runtime, your IDE won't understand them. You can fix this by creating a custom IDE helper file for your macros.
Level up your Laravel deployments
If you aren't happy with your current deployment strategy for your Laravel apps, check out my premium deployment script.
Deploy with GitHub Actions
Deploy with GitLab CI/CD