Home » Php » php – Laravel constructor redirect is not working

php – Laravel constructor redirect is not working

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a controller with several methods and I need to add a specific authorization check on start of each method. So I thought to put this check in constructor as,

class AdminController extends BaseController {

public function __construct() {
    $this->isAuthorized();
}

protected $layout = "layouts.main";

private function isAuthorized() {
    if (!Session::get('userId')) {
        echo "inside check"; // checking for debug purpose
        return Redirect::to('login');
    }
}

/**
 * Admin dashboard view after authentication.
 */
public function getDashboard() {
    $this->layout->content = View::make('admin.dashboard');
}

}

It does not work, it just prints the message inside Session check and load the dashboard page rather than redirecting back to login page.

I have also tried something like this,

 public function getDashboard() {
    $this->isAuthorized();
    $this->layout->content = View::make('admin.dashboard');
}

When I try to call this method with this weird return statement, then it works

public function getDashboard() {
    return $this->isAuthorized();
    $this->layout->content = View::make('admin.dashboard');
}

I get that idea from here.
How do I achieve this using constructor method. Any help is greatly appreciated.

How to&Answers:

Returning a Redirect to execute it is only possible from routes, controller actions and filters. Otherwise you have to call send()

Redirect::to('login')->send();

However you should really use a filter for this

Answer:

Make Sure to use Illuminate\Routing\Redirector; and pass it to the constructor. (Laravel 5.2)

use Illuminate\Routing\Redirector;

class ServiceController extends Controller {

    public function __construct(Request $request, Redirector $redirect) {
        $this->service = Auth::user()->Service()->find($request->id);
        if (!$this->service) {
            $redirect->to('/')->send();
        }
    }

Answer:

Event with Illuminate\Routing\Redirector, laravel set redirect in http header, but also continue to execute request like there are no redirect. So the solution is use die() after the redirection.

public function __construct(Request $request, \Illuminate\Routing\Redirector $redirecor)
{
    //$bool = ...
    if (false == $bool) {
        $redirecor->action('[email protected]')->send() ;
        die();
    }
}