Blues Clues
Blues Clues

Reputation: 1858

Redirect is not working when inside a method in laravel

When I try to put the redirect inside of a method, it won't redirect, but if I put the redirect directly, it will redirect. Please see my code below.

Checking methodThis method will redirect when session is null

private function loadIdChecker()
{
    if(session('load_id') === null) {
        return redirect()->route('load-calculator');
    }
}

Users view method (NOT WORKING)

public function users()
{
  $this->loadIdChecker();

  ... The rest of the code here
}

Users view method (WORKING)

public function users()
{
  if(session('load_id') === null) {
    return redirect()->route('load-calculator');
  }
}

Upvotes: 1

Views: 5238

Answers (4)

Amar pratap singh
Amar pratap singh

Reputation: 227

this works for me

Public function index()
{
   echo  this->checksession();

   "Your other code"

}

public function checksession()
{
   if(Session::get('your_id')== '') 
    {
       return redirect('Yoururl')->with('msg','your message')
    } 
   
}

logic is just remove return and add echo it will show a redirect link but it works

Upvotes: 0

nice_dev
nice_dev

Reputation: 17835

Redirects only work properly when you give the redirect instance to the response handler of Laravel. Right now, it just returns back an instance of Illuminate\Http\RedirectResponse. So, if for some reason, you don't wish to change the method body of load checker, you could just add an additional change as to returning true or whatever at the end to judge the difference in the response as below:

private function loadIdChecker(){
    if(session('load_id') === null) {
        return redirect()->route('load-calculator');
    }
    return true;
}

Then, in your code, you could check like below:

public function users()
{
  $returned_val = $this->loadIdChecker();
  if($returned_val instanceof Illuminate\Http\RedirectResponse){
     return $returned_val;
  }

  // The rest of the code goes here
}

The best way to tackle this is to have a middleware that checks for load_id and redirects to the load-calculator page if load_id is null. Handling redirection via a method is not recommended, especially if it's some kind of auth check.

Upvotes: 1

illusion
illusion

Reputation: 1301

Try: return $this->loadIdChecker(); instead of just $this->loadIdChecker(); in your users() function.

The bug occurs because in your original code the users function is not returning anything while it is expected to return something...

Upvotes: 4

Aless55
Aless55

Reputation: 2709

You will have to add a return statement (and maybe also take into account a case where load_id !== null).

public function users()
{
  return $this->loadIdChecker();
}

Upvotes: 1

Related Questions