php - Laravel loaded relation, called dynamically will not allow ->count() when called in Blade except when in @dd()?

A bit of a weird problem, I'm probably missing something obvious.

I have the following object:

App\Models\Category {#2253 ?�?
  +guarded: []
  +timestamps: false
  #connection: "mysql"
  #table: "categories"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:8 [?��]
  #original: array:8 [?��]
  #changes: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: array:3 [?�?
    "children" => Illuminate\Database\Eloquent\Collection {#2254 ?��}
    "translations" => Illuminate\Database\Eloquent\Collection {#2212 ?��}
    "actions" => Illuminate\Database\Eloquent\Collection {#2257 ?�?
      #items: array:8 [?��]
    }
  ]
  #touches: []
  #hidden: []
  #visible: []
  #fillable: []
]

In the blade the relation (in this case 'actions') is called dynamically in a loop using an array $type, which in this case returns actions and is then to return a count.

{{-- @dd($parent_category->{$type['name']}->count()) --}}

{{$parent_category->{$type['name']}->count()}}
      

In my understanding this should totally work, except it gives the error: Call to a member function count() on null

The weird thing is if I check it with the commented-out @dd, it totally works and returns 8 like it should!

Also if I just write out {{$parent_category->actions->count()}} it works too.

I don't understand why Blade isn't accepting {$type['name']}.

Answer

Solution:

As I understand, you do your dd in a loop and it returns 8 at the first loop but you get the error when you run your code without dd. It means that sometimes $parent_category->{$type['name']} is null and you try to count on null.

Maybe you can try with optional():

{{optional($parent_category->{$type['name']})->count()}}

Like that when it's null it won't try to count and you won't get the error anymore.

Source