简体   繁体   中英

Laravel 5.4 If statement doesn't work in __construct()

Basically this is my __construct of my controller. When non-logged user try go access routes in this controller he is basically redirected to login route. So far so good - if condition is working, redirect is working, route is working.

So next I try to check if users access token is valid and if it's not I will redirect him to logout route - to simplify my example I don't do this but instead I check if $test_var is equal to 1 and redirect to login as we already know this route name as working.

Neither first if($test_var == 1) , not second if($test_var == 1) trigger - there's no redirect or die.

I even tried if(1==1) ..

I even tried to:

 if(isset($this->userCredentials))
         return redirect('login');

and it still doesn't trigger. It's really strange as if I'm not logged first if(!isset... is working and redirects, but this piece of code is doing nothing if I'm logged in:

Looks like the If is the problem, but this If beyond quantum theory obviosly..

This is the full code of the construct:

namespace App\Http\Controllers;

use Input; 
use Session;
use Auth;
use Redirect;

class stackoverflowController extends ConnectionController
{

public function __construct()
{
    $this->middleware('auth');


    $this->userCredentials = Session::get('userCredentials');


    if(!isset($this->userCredentials))
        return redirect('login');

    $test_var = 1;

    if($test_var == 1)
        return redirect('login');

    if($test_var == 1)
        die(1);

    if(1 == 1)
        die(1);
}

I think, If statment works, problem will be in redirect. At least in L4.2 i had same problem, only redirect dont worked.

In laravel 4.2 works send(), but I didnt use it in L5 yet, so pleasy try if it works:

return redirect('login')->send();

Your session isn't be loaded. Edit your Controller __construct to

$this->middleware(function ($request, $next) {
  $this->userCredentials = Session::get('userCredentials');

  if(!isset($this->userCredentials))
    return redirect('login');

  $test_var = 1;

  if($test_var == 1)
    return redirect('login');

  if($test_var == 1)
    die(1);

  if(1 == 1)
    die(1);

  return $next($request);
});

or change your app\\Http\\Kernel.php to

protected $middleware = [
  ...
  \Illuminate\Session\Middleware\StartSession::class,
];

Name your login route as login then try this:

redirect()->route('login');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM