Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

prince69's avatar

How to get all user's data using laravel APi resource ?

I'm trying to get all user's information from User model using api resource. But, I'm getting this error

	"Call to undefined method App\Models\User::mapInto()"

Here is my route

	Route::apiResource('users',UserController::class);

Here is my controller index method

public function index()
{
    return  UserCollection::collection(User::all());
}

Here is the user collection

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class UserCollection extends ResourceCollection
{
/**
 * Transform the resource collection into an array.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
public function toArray($request)
{
    return [
        'first_name' => $this->first_name,
        'last_name'  => $this->last_name,
        'email'      => $this->email,
        'date_of_birth'        => $this->date_of_birth->toDateString(),
    ];
}

}

Does anyone know the solution of this problem?

0 likes
6 replies
martinbean's avatar

@prince69 The issue is you’re extending the wrong class. You’re using your ResourceCollection class as if it were a single resource class.

So, extend just the regular Resource class instead of ResourceCollection, and rename your resource to what it is: UserResource. Your files should then look like this:

return UserResource::collection(User::all());
class UserResource extends Resource
{
    public function toArray($request)
    {
        return [
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'email' => $this->email,
            date_of_birth' => $this->date_of_birth->toDateString(),
        ];
    }
}
prince69's avatar

@martinbean I already have a UserResource class that is used to show single-user data. There are much more fields in the User model. I want to show only selected fields like first_name, last_name, date_of_birth, email into all user API and the rest of the fields will be shown into single user API. That's why I use ResourceCollection

martinbean's avatar

Yes. You’re completely mixing up “regular” resources and collection resources.

A collection resource should transform a collection, not a single model instance like you’re doing.

apex1's avatar

Try return new UserCollection(User::all());

prince69's avatar

It throws an error "Property [first_name] does not exist on this collection instance. "

apex1's avatar

Right my bad. In a resource collection the data is inside $this->collection. Seems as dedicated resource collections are more for including metadata, etc. You might just want to make another UserResource and use what martinbean had suggested. return new SingleUserResource($user); return UserResource::collection($users);

Please or to participate in this conversation.