There is a convenient feature for coding blade templates in Laravel’s view file. It is called ‘directive’. For example, @if
and @endif
.
What if I need a customized directive? How do I do that?
In my case, I have a long statement in the view file to test if the user is a administrator? I use @if
to to do so in the first place. However, it requires the same function in many places and is little annoying to type many words. So I use custom directive to solve this problem and make the code looks more concise.
@if(auth()->check() && auth()->user()->isAdmin())
<div>
:
</div>
@endif
Simple steps:
Just put the code in the boot()
function of the AppServiceProvider.php
. That’s it!
- app/Providers/AppServiceProvider.php
(useif
statement (laravel >= 5.5))
public function boot() {
\Blade::if('isAdmin', function() {
return auth()->check() && auth()->user()->isAdmin();
});
}
Now, it looks more intuitive and concise!
@isAdmin
<div>
:
</div>
@endisAdmin
No comments:
Post a Comment