Irfan Ahmed Irfan Ahmed - 6 months ago 208
PHP Question

Laravel constructor redirect is not working

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.

Answer

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