我对laravel相当新,我试图通过重定向将一些数据发送到我的视图。这就是我的代码:
在我的控制器中:
$tags = Tag::all();
return Redirect::to('klant/profile/edit')->with('tags', $tags);
现在在我看来,我想循环选择字段中的所有标签。我是这样做的:
<select name="filterTags" class="form-control" id="tagsDropdown">
<option value="all">Alle projecten tonen</option>
@foreach (Session::get('tags') as $tag)
<option value="{{ $tag->name }}">{{ $tag->name }}</option>
@endforeach
</select>
但我收到错误:
“为foreach提供的无效参数”
任何人都可以帮助我吗?
任何帮助表示赞赏!非常感谢提前!
答案 0 :(得分:1)
public function index(){
$tags = Tag::all();
return view('welcome',compact('tags'))
}
请确保您的welcome.blade.php
目录中的resources/views/
页面为with()
如果您不想使用return view('welcome')->with('tags','other_variables');
功能,您也可以使用它而不是紧凑型。
List[A]
答案 1 :(得分:0)
要在没有标记时避免此错误,请在您的视图中尝试此操作:
@if ($tags->count())
@foreach ($tags as $tag)
...
@endforeach
@else
No tags
@endif
不以这种方式使用重定向。不要使用重定向来显示视图,使用它来将响应作为错误返回,在索引页面返回等等。我写了一个示例来尝试解释它:
您的索引方法必须如下:
public function index()
{
// find your object
$tags = Tag::all();
// return the view with the object
return View::make('tags.index')
->with('tags', $tags)
}
您的编辑必须如下:
public function edit($id)
{
// find your object
$tag = Tag::find($id);
// if tag doesn't exist, redirect to index list
if (!tag)
{
return Redirect::route('tags.index')
->with('message', "Tag doesn't exist")
}
// return the view with the object
return View::make('tags.edit')
->with('tag', $tag)
}
Laravel文档中的更多示例:https://laravel.com/docs/5.2/responses https://laravel.com/docs/5.2/views