Laravel Gate, policy and supper admin

Posted 1 month ago by danyal14

Hi Guys, I am implementing Gate in my application, where I have following setup.

Users
Roles

Route & policy middleware

Route::get('/expenses/{transaction}', '[email protected]')
        ->name('app.expenses.edit')->middleware('can:update,transaction');

Policy

class TransactionPolicy
{
    use HandlesAuthorization;

    /**
     * Determine whether the user can update the transaction.
     *
     * @param  \App\User  $user
     * @param  \App\Transaction  $transaction
     * @return mixed
     */
    public function update(User $user, Transaction $transaction)
    {
        return $transaction->user_id == $user->id;
    }
}

Til here everything works fine, mean if any other user access the transaction of other user Laravel throws 403.

But as I add before gate and when gate::before returns true SuperAdmin gets access to the transaction but when gate:before returns false, that's me its not a SuperAdmin but a registered user, Laravel throws 403 instead of going to TransactionPolicy.

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        'App\Transaction' => 'App\Policies\TransactionPolicy',
    ];

    /**
     * Register any authentication / authorization services.
     *
     * @param Gate $gate
     * @return void
     */
    public function boot()
    {
        $this->registerPolicies();

        Gate::before(function ($user) {
            return $user->hasRole(Authentication::ROLE_SUPER_ADMINISTRATOR);
                
        });
    }
}

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.