htmlspecialchars() 期望参数 1 为字符串,数组给定 laravel 5.8

htmlspecialchars() expects parameter 1 to be string, array given laravel 5.8

我想显示类别和 paent_id。但是我尝试了但是我没有成功。

category.blade.php

<div class="form-group">
    <label for="parent_id">Category</label>
    <select class="form-control" id="parent_id" name="parent_id">
        <option value="">{{ $categories }}</option>
    </select>
</div>

CategoryController.php

public function create()
{
    $categories = Category::getCatList();
    return view('Admin.categories.create', compact('categories'));
}

Category.php

protected $fillable = ['name', 'parent_id'];

public static function getCatList ()
{
    $array = array();
    $array[0] = 'Main Category';
    $category = self::with('getChild')->where('parent_id', 0)->get();
    foreach ($category as $key => $value) {
        $array[$value->id] = $value->name;
    }
    return $array;
}

public function getChild ()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}

我看到这个错误...

htmlspecialchars() expects parameter 1 to be string, array given (View: C:\xampp\htdocs\new\shopping\resources\views\Admin\categories\create.blade.php)

首先,在.blade中不能不循环使用数组,所以{{ $categories }}是无效的。使用循环:

@foreach($categories AS $category)
  <option value ...>
@endforeach

接下来,您需要传递一些东西以使用值,以及一些东西用作标签。他们现在拥有它的方式,您只传递 $value->name,重构为:

$categories = self::with('getChild')->where('parent_id', 0)->get();
foreach ($categories as $category) {
    $array[$category->id] = $category;
}

然后,在您看来,您可以在每个 option> 中访问 $category->id$category->name

@foreach($categories AS $category)
  <option value="{{ $category->id }}">{{ $category->name }}</option>
@endforeach

以前,您可以这样做:(如果您将代码保持为 $array[$value->id] = $value->name;

@foreach($categories AS $id => $name)
  <option value="{{ $id }}">{{ $name }}</option>
@endforeach

两种方式都可以。