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

farshadf's avatar

how to limit the number of data in where has query laravel

I have a query like so

$data = City::with('hotel')->orwherehas('hotel', function ($query) use ($user_input) {
    //here i want to limit this result to 5
    $query->where('name', 'LIKE', '%' . $user_input . '%')->take(5);
    //                $query->take(5); i have tried this too

})->orWhere('name', 'LIKE', '%' . $user_input . '%')->get();

inside the whereHas clause, I have a query that I want to limit to 5, now I tried limit, take but no luck after that where nothing is working I don't know why

0 likes
2 replies
ftiersch's avatar

You cannot use limit in subqueries, that limits the "outer query". But why would you need a limit in a "whereHas"? whereHas only checks if a relation exists so it's true or false. You need to put the limit inside your with()

1 like
farshadf's avatar

yes you are right but can i limit the results in my resource ?? i am loading my resource this way :

 return [
            'id' => $this->id,
            'name' => $this->name,
            'hotel' => hotelJustNameResource::collection($this->whenLoaded('hotel')),
        ];

Please or to participate in this conversation.