How to redirect to a route from a controller method

假如想象 提交于 2019-12-01 00:03:51
Jithin Jose

You can use redirect() method.

return redirect()->route('route.name')->with(['email'=> 'abc@xys.com']);

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')

You will need to define the route to which you want to redirect()

return redirect()->route('profile')->with('credentials', $credentials);

The with option flashes data to the session which can be accessed as if passed to the view directly.

More information regarding the session and flashing data can be found here.

Information regarding flashing data after a redirect can be found here.

In your case you could use:

return redirect()->route('profile')->with('email', $credentials['email']);

In your view you could then use it like:

@if(session()->has('email')
    We have the email of the user: {{ session('email') }}
@endif

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 :)

Please change your view path like :

return view('welcome', compact(credentials));

return redirect()->route('profile')->with('credentials',$credentials);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!