Engineering note · Laravel
Custom Blade Directives in Laravel
Laravel allows you to create custom Blade directives, making it easier to reuse and organize common code in your views.
By Farah Jokhio Published
Step 1: Create a Custom Blade Directive
Add custom directives in the boot method of a service provider, such as AppServiceProvider.
use Illuminate\Support\Facades\Blade;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
// add blade directive like this
Blade::directive('greet', function ($name) {
return "<?php echo 'Hello, ' . ucfirst($name) . '!'; ?>";
});
}
}
Here, @greet('world') will output "Hello, world!" in your view.
Step 2: Use the Custom Directive in Your Blade File
In any Blade file, use the @greet directive:
<!-- welcome.blade.php -->
@php
$userName = 'john';
@endphp
<p>@greet($userName)</p>
This will render:
<p>Hello, John!</p>
Another Example: Custom Auth Check Directive
Add a custom directive to check if the user is an admin.
Blade::if('admin', function () {
return auth()->check() && auth()->user()->is_admin;
});
Then, in your Blade file:
@admin
<p>Welcome, Admin!</p>
@endadmin
This will show the message only if the logged-in user is an admin.
Custom Blade directives make repetitive tasks easier to handle, allowing to create cleaner and more maintainable views.
Use them to simplify your templates!
More engineering notes
Minimize Direct Queries in Blade Views
Avoid executing database queries directly within Blade templates. Instead, fetch data in the control...
Use Query Scopes for Reusable Queries
Encapsulate common query logic within model scopes to keep your code DRY (Don't Repeat Yourself). Sc...