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?
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
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();
}
}
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('MyController@myAction')->send() ;
die();
}
}
Use ->send()
redirect()->route('named-route')->send();insted of
return
return redirect()->route('named-route');in Laravel Constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With