0

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.

1
  • since your $tags2 is an array, you cant access its properties as object notation. you need to use array notation in your blade file. <option value="{{$tag['id']}}">{{$tag['name']}}</option> Commented Apr 11, 2019 at 3:44

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

That worked fantastic! Thank you. What is the "pluck" in the Tag::pluck() if you don't mind me asking??
search pluck word
Retrieving A List Of Column Values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.