If you're using the same condition repeatedly in Blade, especially if it's complex, you likely won't want to repeat it multiple times. To avoid this, Laravel provides a neat way to define your condition once in the AppServiceProvider class:
use Illuminate\Support\Facades\Blade;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::if('isGuest', function () {
return auth()->guest();
});
}
Then, you can easily use it like this:
@isGuest
<p>You are a guest</p>
@endisGuest
In addition, you can define a custom Blade directive like this:
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Blade::if('isAuth', function () {
return auth()->check();
});
Blade::directive('welcomeUser', fn($name) => "Welcome $name");
}
Once defined, you can use these custom directives in your Blade templates like this:
@isAuth
@welcomeUser(auth()->user()->name)
@endisAuth