Reputation: 348
I am fairly new to laravel and I am trying to send some data to my view via redirect. This is what my code looks like:
In my controller:
$tags = Tag::all();
return Redirect::to('klant/profile/edit')->with('tags', $tags);
Now In my view I want to loop over all the tags in a select field. I do this like so:
<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>
But I get the error:
"invalid argument supplied for foreach"
Can anyone help me out?
Any help is appreciated! Many thanks in advance!
Upvotes: 0
Views: 3062
Reputation: 5230
To avoid this error when you don't have tags, try this in your view:
@if ($tags->count())
@foreach ($tags as $tag)
...
@endforeach
@else
No tags
@endif
Not use redirects at this way. Don't use redirect to show a view, use it to return responses as errors, to return at index page, etc. I wrote an example to try to explain it:
Your index method must be like this:
public function index()
{
// find your object
$tags = Tag::all();
// return the view with the object
return View::make('tags.index')
->with('tags', $tags)
}
Your edit like must be like this:
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)
}
More examples at Laravel docs: https://laravel.com/docs/5.2/responses https://laravel.com/docs/5.2/views
Upvotes: 0
Reputation: 5099
public function index(){
$tags = Tag::all();
return view('welcome',compact('tags'))
}
Just make sure you've page called welcome.blade.php
in your resources/views/
directory
If you wan't to use with()
function you can use it also instead of compact.
return view('welcome')->with('tags','other_variables');
Upvotes: 1