0

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

ottz0
  • 2,595
  • 7
  • 25
  • 45
  • In your blade file, `$categories` is an array and you're trying to `echo` it (`{{$category}}`). – Laralex Jul 11 '22 at 08:14
  • Does this answer your question? [Laravel - htmlspecialchars() expects parameter 1 to be string, object given](https://stackoverflow.com/questions/43217872/laravel-htmlspecialchars-expects-parameter-1-to-be-string-object-given) – SEYED BABAK ASHRAFI Jul 11 '22 at 08:18

2 Answers2

2

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
mrhn
  • 17,961
  • 4
  • 27
  • 46
-1

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
Mehran
  • 282
  • 1
  • 6
  • 17