从控制器重定向并传递数据 [英] Redirect and pass data from controller

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

问题描述

我想从控制器重定向并传递数据;

I want to redirect from a controller and pass data;

 public function fortest(Request $request)
{
     $user = DB::table('user2s')->where('name', $request->name)->first();
     if (isset($user))
     {   
        return redirect('/fortest2', ['user'=>$user]);//compact('user'));
        //return $this->fortest2($request);
     }
}
public function fortest2(Request $request)
{
    return $request->name;
}

Route::get('/fortest', 'UserController@fortest');
Route::get('/fortest2/', 'UserController@fortest2');

直接从控制器内部调用控制器时,该代码有效.数据类型具有模型.我该怎么做?

The code works when calling the controller directly from within the controller. The data type has a model. How can I accomplish this?

推荐答案

如果要在重定向中传递数据,则可以使用 with()方法.您必须像这样将其附加到重定向中:

If you want to pass data in a redirect, you can use the with() method. You have to append it to the redirect like so:

redirect('/fortest2')->with('data', 'value');

它将保存在您当前的会话中,因此它将保持不变,直到您再次刷新页面为止.如果要存储更长的时间,则必须使用数据库/文本文件等.然后可以使用

It will be saved in your current session, so it will be only persistent until you refresh the page again. If you want to store it for longer you have to go with a database/textfile etc. You can then check for it using

if (session()->has('data')) { // check if it exists
    $value = session('data'); // to retrieve value
}

您还可以使用 withErrors()通过重定向发送错误(例如,通过验证),使用 withInput()

You can also send errors with the redirect (from validation i.e.) using withErrors(), sending the current input with it using withInput()

对于要实现的目标,请尝试在控制器中使用它.这只会通过重定向发送用户名:

For what you want to achieve, try using this in your controller. This will just send the users name with the redirect:

$user = DB::table('user2s')->where('name', $request->name)->first();
redirect('/fortest2')->with('username', $user->name);

然后您可以通过 session('username')

这篇关于从控制器重定向并传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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