i am trying to use constructor in controller but failed !Why my constructor not working?

50 Views Asked by At
public function __construct()
{
     if (Auth::check()){
        if(Auth::user()->user_type == 'admin'){
            return to_route('admin.dashboard');
        } elseif(Auth::user()->user_type == 'operator'){
            return to_route('operator.dashboard');
        }
     }
}

I am checking user authentication.

3

There are 3 best solutions below

0
Karl Hill On

Create a controller method, don't do it in the constructor. Constructors in Laravel controllers do not typically return values.

public function someMethod()
{
    if (Auth::check()) {
        if (Auth::user()->user_type === 'admin') {
            return redirect()->route('admin.dashboard');
        } elseif (Auth::user()->user_type === 'operator') {
            return redirect()->route('operator.dashboard');
        }
    }

    //...
}
1
Marcin Nabiałek On

It's not possible by design. If you need it you can create middleware in constructor like this:

public function __construct()
{
    $this->middleware(function ($request, $next) {
        if (Auth::check()){
           if(Auth::user()->user_type == 'admin'){
              return to_route('admin.dashboard');
           } elseif(Auth::user()->user_type == 'operator'){
              return to_route('operator.dashboard');
           }
         }
 
         return $next($request);
    });
}

but you can also create normal middleware and use it for controller.

See this Laravel change to get more explanation

0
shekib quraishy On

After user login you are redirecting the users to a route and that route points to a function, so basically you can implement this with a middleware or a simple function of redirect instead of constructor which is to initialize an object's properties.

 public function redirect()
    {
        $role = Auth::user()->role;
        return match ($role) {
            'Admin' => redirect('/admin/dashboard'),
            'Operator' => redirect('/operator'),
        };
    }