2
votes

I'm trying to create a blade directive that checks if the User is logged in AND has an activated account. In our database, we have a user_status column with 0: pending, 9 active.

// AppServiceProvider.php

public function boot()
{
    Blade::directive('active', function () {
        $condition = false;

        // check if the user is authenticated
        if (Auth::check()) {
            // check if the user has a subscription
            if(auth()->user()->getStatus() == 9) {
                $condition = true;
            } else {
                $condition = false;
            }
        }

        return "<?php if ($condition) { ?>";
    });

    Blade::directive('inactive', function () {
        return "<?php } else { ?>";
    });

    Blade::directive('endactive', function () {
        return "<?php } ?>";
    });
}

// welcome.blade.php

@active
    <p>User is active</p>
@inactive
    <p>User is inactive</p>
@endactive

I have included this getStatus() function on my User.php model.

public function getStatus() {
    return $this->user_status;
}

I can also use the Trait MustActivateAccount, which includes this feature:

/**
 * Determine if the user has activated account.
 *
 * @return bool
 */
public function hasActivatedAccount()
{
    return $this->user_status == 9;
}

This blade directive when added to the page says this error:
Facade\Ignition\Exceptions\ViewException syntax error, unexpected ')'

Am I not escaping correctly in the AppServiceProvider.php file and if so where and how?

2
instead of this auth()->user()->getStatus() == 9 use Auth::user()->getStatus() == 9 - Gabrielle-M
I don't think that error from blade directive, I've just tested your code and it's working fine. You need to check log to see more details. - Sang Nguyen
@Josh did you solve this problem? - parth

2 Answers

3
votes

You can try this in your blade template

@if(Auth()->user()->user_status == 9)
    <p>User is active</p>
@else
    <p>User is inactive</p>
@endif
1
votes

I had the same issue and the solution turned out to be the boolean $condition variable that had to be set as a string. $condition = "true"; and not $condition = true.

This makes sense since the boolean would not echo out. Thus it would be <?php if() { ?> and not <?php if(true) { ?>.

See below (current version 6.18.41):

// check for Providers
Blade::directive('provider', function () {
   // check if the user has the correct type
   $condition = Auth::user()->type === "provider" ? "true" : "false"; // ... and not boolean
   return "<?php if (" . $condition . ") { ?>";
});
Blade::directive('endprovider', function () {
   return "<?php } ?>";
});

... and run: php artisan view:clear