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

raziel79's avatar

laravel 5.5 API resource Call to undefined method Illuminate\Database\Query\Builder::mapInto()

i have Post and User model with one to one relation and it works good:

    //User.php

    public function post(){
        return $this->hasOne(Post::class);
    }


    // Post.php

    public function user() {
        return $this->belongsTo(User::class);
    }

now i create API resources:


    php artisan make:resource Post
    php artisan make:resource User

I need to return all post with an api call then i set my route:

    //web.php: /resource/posts

    Route::get('/resource/posts', function () {
        return PostResource::collection(Post::all());
    });

this is my Posts resource class:

    <?php

    namespace App\Http\Resources;
    use Illuminate\Http\Resources\Json\Resource;
    use App\Http\Resources\User as UserResource;

    class Posts extends Resource
    {
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
          return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'bodys' => $this->body,
            'users' => UserResource::collection($this->user),
            'published' => $this->published,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
      
    }
    }

this is the error:

    Call to undefined method Illuminate\Database\Query\Builder::mapInto()

if i remove:

    'users' => UserResource::collection($this->user),

it's work but i need to include relations in my api json, i have read and followed the doc at https://laravel.com/docs/5.5/collections.

this is my User resource class:

    <?php

    namespace App\Http\Resources;

    use Illuminate\Http\Resources\Json\Resource;

    class User extends Resource
    {
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
       return [
           'user_id' => $this->user_id,
           'name' => $this->name,
           'lastname' => $this->lastname,
           'email' => $this->email
       ];
    }
    }

any ideas where am i wrong?

0 likes
2 replies
KamalKhan's avatar

$this->user is not a collection so you shouldn't be using

UserResource::collection($this->user)

This is what you should use for model instances:

new UserResource($this->user)
1 like
srikanthgopi's avatar

Resource::collection is used when the model has hasMany relation. If your model has hasOne relation use Resource::make(Post::all())

Please or to participate in this conversation.