Reputation: 249
I'm trying to loop through an array in one of my controllers in Laravel app and then pass it through to view.
It is currently throwing error "Trying to get property of non-object" which tells me the array is returning as null?
In my controller below, I am trying to set an array as empty by default and then pass in values to that array before passing it to the view, like so:
Recipe Controller
public function edit($id)
{
$recipe = Recipe::find($id);
$tags = Tag::all();
$tags2 = array();
foreach ($tags as $tag){
$tags2[$tag->id] = $tag->name;
}
return view('recipes.edit')->with('recipe', $recipe)->with('tags', $tags2);
}
and my view
<fieldset>
<small class="errorMessage"></small>
<label for="tags">Tags</label>
<select name="tags[]" id="tagsList" class="select2-multi" multiple="multiple">
@foreach($tags as $tag)
<option value="{{$tag->id}}">{{$tag->name}}</option>
@endforeach
</select>
</fieldset>
The point of this is to update existing tags on a recipe (my recipes are the equivalent of posts on this application). Storing and displaying tags works fine, but the edit is where I am having trouble. Please let me know if you see something that I don't.
Upvotes: 0
Views: 513
Reputation: 8618
use this code
public function edit($id)
{
$recipe = Recipe::find($id);
$tags = Tag::pluck('name', 'id');
return view('recipes.edit')->with('recipe', $recipe)->with('tags', $tags);
}
in view
@foreach($tags as $id => $name)
<option value="{{$id}}">{{$name}}</option>
@endforeach
Upvotes: 3