如何从控制器方法重定向到路由



我在控制器中定义了一个方法,首先检索输入,如果电子邮件字段存在于我的数据库中,我想返回一个视图。但是,如果电子邮件字段不存在,我想重定向到另一条路由。我还想将输入传递到该路线。

为了更好地理解我的意思,我的控制器的代码如下:

public function index(Request $request) {
$credentials = $request->all();
if (AppUser::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);
}

我的网络.php如下:

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

但是,此逻辑失败并显示错误:"未定义 HTTP 状态代码'1'"。 有没有办法正确地做到这一点?(即从我的控制器方法转到另一个路由?

您可以使用redirect()方法。

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

由于将with()redirect()一起使用会将"电子邮件"添加到会话(而不是请求(。然后使用以下内容检索电子邮件:

request()->session()->get('email')
//Or
session('email')

虽然@JithinJose问题给出了答案,但我将此添加为那些将来考虑这个问题的人的答案,并且不想在会话中处理这样的事情:

不推荐的方法是直接从此控制器方法调用控制器,并将所需的变量传递给它:

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

如果另一个控制器方法存在于同一个类中,这将没问题,否则你只需要获取你需要的方法并重用它。

如果要避免会话,最佳推荐方法是重定向到控制器操作,即:

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

我希望它有用:)

您需要定义要redirect()的路由

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

with选项将数据闪烁到会话,可以像直接传递到视图一样访问该会话。

有关session和闪烁数据的更多信息,请参见此处。

有关重定向后闪烁数据的信息,请参阅此处。

在您的情况下,您可以使用:

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

在您看来,您可以像这样使用它:

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

请更改您的视图路径,例如:

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

最新更新