Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vedoj's avatar
Level 1

Why isn't this use($user) working in Blade::if() ?

I have asked how to simplify some code here:

https://laracasts.com/discuss/channels/code-review/ways-to-optimize-this-code-of-custom-blade-guards-in-appserviceprovidersphp

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?

0 likes
4 replies
Snapey's avatar

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

Sinnbeck's avatar

I thought you actually had tested it. I was curious that it worked but never tested it myself

vedoj's avatar
Level 1

@Sinnbeck I just duplicate it everywhere then. Or do you think it can be somehow improved? In the end I have like 10 or so guards but still.

Snapey's avatar

@vedoj You can simplify a little

    Blade::if('user', function () {
        return auth()->check() && auth()->user()->role_id === 1;
    });
    

Please or to participate in this conversation.