Home > Mobile >  Laravel Resource Collection: "Undefined property: Illuminate\\Database\\Query\\Builder::$
Laravel Resource Collection: "Undefined property: Illuminate\\Database\\Query\\Builder::$

Time:11-30

I am currently trying out Laravel Resource. Single resource works fine. But Resource Collection throws me the following error:

"Undefined property: Illuminate\Database\Query\Builder::$map"

UserController.php

use App\Http\Resources\UserResource;
use App\Http\Resources\UserCollection;
use App\Models\User;

class UserController extends Controller
{
   public function index()
    {
        return [
            'success' => true, 
            'data' => new UserCollection(User::all())
        ];        
    }

     public function show(User $user)
     {
        return [
            'success' => true, 
            'data' => new UserResource($user)
        ];
    }
}

UserCollection.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
    public function toArray($request)
    {
        $count = $this->collection->count();
        
        return [
            'count' => $count,
            'data' => $this->collection
        ];
    }
}

The error clearly comes from this line: 'data' => $this->collection. I suspect $this->collection iterates over the user collection. If I dd($this->collection) I correctly get all 51 items from the database. from the database:

output dd($this->collection) inside resource collection)

Illuminate\Support\Collection {#1380 ▼ //
app/Http/Resources/UserCollection.php:18
  #items: array:51 [▶]
  #escapeWhenCastingToString: false
}

What do I have to change to make it work? Thanks in advance, Mike!

CodePudding user response:

I guess you want something like this?

return [
    'count' => $count,
    'data' => UserResource::collection($this->collection)
];
  • Related