Laravel控制器中如何将变量从store方法传递至index方法?
解决方法
因为store方法执行后会重定向到index,这是两个独立的HTTP请求,无法直接传递变量,你可以用以下两种常用方式实现:
方式一:Session闪存(推荐,适合临时传递数据)
步骤1:修改store方法,通过重定向携带闪存数据
public function store(Request $request) { $user = new User($request->all()); $user->save(); $test = "test"; // 使用redirect的with方法将数据存入session闪存 return redirect('users')->with('test', $test); }
步骤2:在index方法中取出数据并传递到视图
public function index() { // 从session中取出闪存数据(仅当前请求有效,下次请求自动清除) $test = session('test'); return view('users.index', [ 'users' => User::all(), 'test' => $test ]); }
或者无需修改index方法,直接在index.blade.php视图中读取session数据:
<!-- 在index.blade.php中展示 --> @if(session('test')) <p>{{ session('test') }}</p> @endif
方式二:URL查询参数(适合非临时数据,参数会暴露在URL中)
步骤1:修改store方法,重定向时携带查询参数
public function store(Request $request) { $user = new User($request->all()); $user->save(); $test = "test"; // 将参数拼接到重定向URL中 return redirect('users?test=' . $test); }
步骤2:在index方法中获取查询参数并传递到视图
public function index(Request $request) { // 从请求中获取查询参数 $test = $request->query('test'); return view('users.index', [ 'users' => User::all(), 'test' => $test ]); }
内容的提问来源于stack exchange,提问作者Brek
相关产品推荐
相关产品推荐

