Best way to redirect after login depends on user role



  • I am wondering what is the best way to redirect users depends on their role.

    I have different roles, teacher, student, administrator, secretary etc. After login, I'd like to redirect to different controller.


  • Global Moderator

    @shinokada

    Hey,

    If you are using default authentication driver Sentinel then you can listen for event sentinel.authenticated which passes User object to you.
    Then you can figure out what user role group is part of and redirect accordingly.



  • So you suggest to create Event classes in app/Events and app/Listeners and put redirect logic there?


  • Global Moderator

    I would create event classes in your module, that has those controllers where you want to redirect user.
    If you are creating controllers in app/Http then you are missing out on modularity of asgard.



  • Q1. Where does it control after login in the default codes? For example Admin is redirected to dashboard and User is redirected to the front page.

    Q2. If I create a module with events, where should I register events subscriber?


  • admin

    I had to do the same kind of logic on a current application, and ended up forking the user module to adapt that logic.

    @armababy 's method might be even cleaner :)


  • Global Moderator

    @shinokada

    By default, it always redirect you to the page you was when you performed login or to homepage.

    For module approach you can generate new module something like php artisan asgard:module:scaffold name it somehow like Redirector.
    From there you can look into Asgard modules how are they handling events.

    Basically you have to list your listeners in ServiceProvider, point them to handlers.

    Create folder in your module something like Events/Handlers or Handlers create your handler classes there.
    Add this to your modules service provider:

        protected $listen = [
            'sentinel.authenticated' => [
               'Modules\MyModule\Events\Handlers\MyHandler',
            ],
        ];
    

Log in to reply