简体   繁体   中英

Laravel Horizon - gate with different guard

I would like to use admin guard for authorise viewing laravel horizon but I have to be logged in as user AND as admin.

Here is my code for HorizonServiceProvider.php

class HorizonServiceProvider extends HorizonApplicationServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        // Horizon::routeSmsNotificationsTo('15556667777');
        // Horizon::routeMailNotificationsTo('example@example.com');
        // Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel');

        // Horizon::night();
    }

    /**
     * Register the Horizon gate.
     *
     * This gate determines who can access Horizon in non-local environments.
     *
     * @return void
     */
    protected function gate()
    {
        Gate::define('viewHorizon', function () {
            return \Auth::guard('admin')->check();
        });
    }
}

It works OK if I am logged in as used AND admin. But when I am logged in only as admin the result from gate is:

array:4 [▼
  "ability" => "viewHorizon"
  "result" => null
  "user" => null
  "arguments" => "[0 => null]"
]

Thanks for help

Probably too little too late for you, but for others searching the issue:

Laravel assumes that you use the default "web" guard and it is injecting the authenticated user (so it forces the "web" guard check).

As specified in the docs (see big "!" note), to force Laravel to not require "web" guard authentication you just need to specify $user = null , and then you can implement whatever you want.

So your case the gate function in the HorizonServiceProvider class should be something like this:

protected function gate() {

    Gate::define('viewHorizon', function ($user = null) {
        return Auth::guard('admin')->check();
    });

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM