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

时间:2019-05-21 16:41:02

标签: 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()期望参数1为字符串,为给定的数组(视图:C:\ xampp \ htdocs \ new \ shopping \ resources \ views \ Admin \ categories \ create.blade.php)

1 个答案:

答案 0 :(得分:0)

首先,您不能在.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;
}

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

@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

任何一种都可以。