dqroktbn005028 2016-10-07 11:36
浏览 114
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • doutai1509 2016-10-07 11:38
    关注

    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
    }
    

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

    You can then access is via session('username')

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历