Avi6033's avatar

i think in my code withwherehas load relationship of "rooms" even when return false

public function __invoke(SearchRequest $request)
    {

        $hotels = Hotel::query()
       
        ->when($request->address, function ($query) use ($request) {

            $query->where('address', $request->address);

        })->withwherehas('rooms', function($query) use ($request) {

            $query->when ($request->adults && $request->children , function($query) use ($request){

                $query->where('adults', '>=' , $request->adults)
                ->where('children', '>=' ,$request->children);
            }) 
            ->when ($request->from_price && $request->to_price , function($query) use ($request){

                $query->whereBetween('price',[$request->from_price,$request->to_price ]);
                
            });
        })
        ->get();
0 likes
2 replies
Avi6033's avatar

If someone has tips for improving the code? tell me And thank you in advice

jaseofspades88's avatar

Define 'improving your code' here. If it's an API request, use an API resource. If you're not willing to use query scopes consider cleaning it up and using short closures. If you're talking performance, consider caching.

Too many possible answers to such a vague question but I would recommend leveraging custom query builders to clean up this mess... This article is really good and easy to follow... https://martinjoo.dev/build-your-own-laravel-query-builders..

Another thing don't couple your query builders to the request class as you are doing here, simply pass the values as strings.

1 like

Please or to participate in this conversation.