简体   繁体   English

试图访问数组的控制器中的Laravel 5.8问题

[英]Laravel 5.8 issue in controller trying to access array

I'm trying to loop through an array in one of my controllers in Laravel app and then pass it through to view. 我试图在Laravel应用中的一个控制器中循环遍历一个数组,然后将其传递给视图。

It is currently throwing error "Trying to get property of non-object" which tells me the array is returning as null? 当前正在抛出错误“试图获取非对象的属性” ,该错误告诉我数组返回为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. 如果您看到我看不到的内容,请告诉我。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM