将 $variable 发送到 Laravel 5 中的视图

Send $variable to a view in Laravel 5

我有一个 $alerts 变量数组。

看起来像这样

array:3 [▼
  0 => array:3 [▼
    "status" => 200
    "message" => "Success"
    "data" => []
  ]
  1 => array:3 [▼
    "status" => 200
    "message" => "Success"
    "data" => []
  ]
  2 => array:3 [▼
    "status" => 404
    "error_code" => 35
    "message" => "invalid json - api not supported"
  ]
]

我想将它从我的控制器发送到我的视图。

我试过了

控制器

return Redirect::to('/account/'.$id) ->with('alerts',$alerts)

路线

我的路线:http://localhost:8888/account/1007

查看

我试过这样访问

{!!$alerts!!}

然后,我尝试像这样访问它,但我一直得到

Undefined variable: alerts

您尚未发布实际加载视图的代码。当您 return a Redirect->with(...) 时,您所做的就是将变量传递给下一个请求。在为 account/{id} 路由提供服务的控制器中,您需要 return view('viewname', ['alerts' => session('alerts')])

试试这个:

Session::flash('alerts', $alerts);
return route('ROUTENAME', $id);

只需更改路由名称中的 ROUTENAME(如果在 routes.php 中定义)。

例如:

Route::get('account/{id}', ['as' => 'account.show', 'uses' => 'AccountController@show']);

在此示例中,ROUTENAME 将为 'account.show'


在您看来,您可以通过以下方式访问它:

Session::get('alerts');

信息: - http://laravel.com/docs/5.1/session#flash-data

Sometimes you may wish to store items in the session only for the next request. You may do so using the flash method.

根据 Laravel documentation on redirects,当使用 with() 重定向时,它会将数据添加到 session,而不是作为视图变量。因此,您需要像这样访问它:

@foreach (session('alerts') as $alert)
    <p>{{ $alert['message'] }}</p>
@endforeach