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

thedome's avatar

Query with relation

Heyyo,

I have the User

public function buildings()
    {
        return $this->hasMany('MyApp\Building');
    }

And Buildings

public function user()
    {
        return $this->belongsTo('MyApp\User');
    }

Now I want to paginate the Buildings but it don't work...

public function index()
    {
        $buildings = Building::whereHas('user', function ($query) {
            $query->where('user_id','=',Auth::id());
        })->paginate(15);

        return BuildingResource::collection($buildings);
    }

Does someone see my mistake?

0 likes
1 reply
tykus's avatar

Not need for a whereHas - the underlying query in your case expects a user_id field on the users table. Do the following instead:

$buildings = auth()->user()->buildings()->paginate(15);

Please or to participate in this conversation.