because the blade code runs when the view is rendered
your $user = Auth::user() outside of the function only runs when the boot method of the provider is called
any consolation, callbacks took me the longest time to get my head around
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have asked how to simplify some code here:
People suggested some things how to improve my code.
Among them moving $user = Auth::user(); outside of Blade::if and importing it via use($user) into the function scope like this:
public function boot()
{
$user = Auth::user();
Blade::if('user', function () use ($user) {
return $user && $user->role_id === 1;
});
Blade::if('editor', function () use ($user) {
return $user && $user->role_id === 2;
});
However, today I was using those guards in my template and it's not working for some reason and I have to go back to more wordy code:
public function boot()
{
Blade::if('user', function () {
$user = Auth::user();
return $user && $user->role_id === 1;
});
Blade::if('editor', function () {
$user = Auth::user();
return $user && $user->role_id === 2;
});
Which works.
Any idea how to make it work by abstracting $user = Auth::user() somehow and importing $user in Blade:;if() so it works?
Please or to participate in this conversation.