Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect to a route from a controller method

I have defined a method in my controller, where inputs are first retrieved, and if the email field is present in my database, I would like to return a view. However, if the email field isn't present, I would like to redirect to another route. I would also like to pass in the inputs to that route as well.

To better understand what I mean, my code is as follows for my controller:

    public function index(Request $request) {

    $credentials = $request->all();

    if (\App\User::where('email','=',$credentials['email'])->exists()){

        //if they are registered, return VIEW called welcome, with inputs

        return view('welcome', $credentials);

    }
    else{//If the user is not in the database, redirect to '/profile' route,
         //but also send their data

        return redirect('profile', $credentials);

    }

And my web.php is as follows:

Route::post('/profile', function() {
     $m = Request::only('email'); //I only need the email
     return view('profile', $m);
});

However, this logic fails with errors: 'HTTP status code '1' is not defined'. Is there anyway to do this properly? (i.e. go from my controller method to another route?)

like image 367
Muhammad Avatar asked Dec 18 '22 05:12

Muhammad


2 Answers

You can use redirect() method.

return redirect()->route('route.name')->with(['email'=> '[email protected]']);

Since using with() with redirect() will add 'email' to the session (not request). Then retrieve the email with:

request()->session()->get('email')
//Or
session('email')
like image 179
Jithin Jose Avatar answered Jan 05 '23 18:01

Jithin Jose


While @JithinJose question gave the answer, I am adding this as answer for those who consider this in the future, and who does not want to deal with getting things like this in the session:

A not-recommended way to do this is to call the controller directly from this controller method, and pass the variable needed to it:

$request->setMethod('GET'); //set the Request method
$request->merge(['email' => $email]); //include the request param
$this->index($request)); //call the function

This will be okay if the other controller method exists within the same class, otherwise You just have to get the method you need and reuse it.

The best recommended way if you want to avoid session is Redirect to controller action i.e:

return redirect()->action(
   'UserController@index', ['email' => $email]
);

I hope it is useful :)

like image 38
Oluwatobi Samuel Omisakin Avatar answered Jan 05 '23 17:01

Oluwatobi Samuel Omisakin