2016-06-20 39 views
0

我对laravel相当新,我试图通过重定向将一些数据发送到我的视图。这是我的代码如下所示: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> 

但我得到的错误:

"invalid argument supplied for foreach"

谁能帮助我吗?

任何帮助表示赞赏!提前谢谢了!

+2

这不是一个很好的处理方法。为什么不在处理'klant/profile/edit'的函数中获取'$ tags'? – ceejayoz

+0

当没有闪烁的标签数据时抛出错误。你应该检查参数的存在,但为什么闪烁的雄辩模型?这很不寻常。 – undefined

+0

你的laravel版本是什么?而且,你是否尝试过dd(Session)? – Mojtaba

回答

1
public function index(){ 
    $tags = Tag::all(); 
    return view('welcome',compact('tags')) 
} 

只要确保你在你的resources/views/目录

打过电话welcome.blade.php页。如果您wan't使用with()功能,你也可以用它代替紧凑。

return view('welcome')->with('tags','other_variables'); 
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/responseshttps://laravel.com/docs/5.2/views

相关问题