Home > Enterprise >  Laravel Blade must be of type string, array given
Laravel Blade must be of type string, array given

Time:07-11

I learning Laravel and have a recursive table that I need to loop through to get the null values as I need to then get the id's that they are linked to in order show the articles.

How can I loop through this in my blade template?

Blade view is returning... htmlspecialchars(): Argument #1 ($string) must be of type string, array given

Blade Template

@foreach ($categories as $category)
       {{$category}}
@endforeach

Controller

$categories = array();
    $parentCategories = Category::where('parent_id', null)->get();

    foreach($parentCategories as $parentCategory){
            $categories[] = Category::where('parent_id',$parentCategory->id)->with('articles')->get();
    };

    return view('marketplace.categories.index', [
        'categories' => $categories
 ]);

Database Table

enter image description here

CodePudding user response:

get() returns a collection of categories, so you probably wanted to do a loop in a loop. Since there are multiple categories with the same parent_id.

@foreach ($categories as $parentCategories)
    @foreach($parentCategories as $parentCategory)
        {{ $parentCategory->title }}
    @endforeach
@endforeach

CodePudding user response:

In controller try to change get to first, change:

 foreach($parentCategories as $parentCategory){
        $categories[] = Category::where('parent_id',$parentCategory->id)->with('articles')->get();
};

to

 foreach($parentCategories as $parentCategory){
        $categories[] = Category::where('parent_id',$parentCategory->id)->with('articles')->first();
};

also in blade you should point to field name as an example:

 @foreach ($categories as $category)
       {{$category->title}}
    @endforeach
  • Related