isadma
2 weeks ago

Add a custom item to eloquent collection

Posted 2 weeks ago by isadma

I am using Laravel 7.

I have Category model. I sent categories as API with laravel resources. But now I want to add "all" value to categories.

Controller:

'categories' => CategoryResource::collection(Category::all()->push([
      'id' => 0,
      'name' => "All",
      'subcategories' => []
 ]))

My resource:

public function toArray($request)
{
     return [
          'id' => $this->id,
          'name' => $this->name,
          'subcategories' => SubcategryResource::collection($this->subcategories)
     ];
}

Also, I wanted to add this custom value to the beginning of the collection.

But I am getting this error:

Trying to get property 'id' of non-object

Please, help me. How can I solve my problem?

Please sign in or create an account to participate in this conversation.