Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 987
Irfan Ahmed Avatar asked Dec 19 '14 14:12

Irfan Ahmed


4 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

like image 52
lukasgeiter Avatar answered Nov 14 '22 02:11

lukasgeiter


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();
        }
    }
like image 44
Dumindu Perera Avatar answered Nov 14 '22 03:11

Dumindu Perera


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();
    }
}
like image 2
Omar Ghorbel Avatar answered Nov 14 '22 04:11

Omar Ghorbel


Use ->send()

redirect()->route('named-route')->send();
insted of return
return redirect()->route('named-route');
in Laravel Constructor.
like image 2
Chandan Mistry Avatar answered Nov 14 '22 03:11

Chandan Mistry