如何从控制器方法重定向到路由 [英] How to redirect to a route from a controller method

查看:179
本文介绍了如何从控制器方法重定向到路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    }

我的web.php如下:

And my web.php is as follows:

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

但是,此逻辑失败并出现错误:未定义HTTP状态代码'1'". 反正有适当的做这件事吗? (即从我的控制器方法转到另一条路线?)

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

推荐答案

您可以使用redirect()方法.

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

由于将with()redirect()结合使用,会将'电子邮件'添加到会话(非请求).然后通过以下方式检索电子邮件:

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

这篇关于如何从控制器方法重定向到路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆