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

Johny22's avatar

Query filter

Hi, I would like to consult / ask. I wrote a query which I extract data from the database that will come with the request according to the country code and dimensions. Everything works. Is this function written well and correctly? Well thank you.

public function getDimensions(SearchDimensionRequest $request)
    {
        $dimensions = Country::where('country_code', $request->selectedCountry)
            ->first()->categories()->where('max_dimension', '>=', $request->dimension)
            ->orderBy('max_dimension', 'asc')->get();

        $firstDimension = $dimensions->first();
        $firstDimension->priceHtml = Cash::formatAmount($firstDimension->pivot->price);

        return $firstDimension;
    }

0 likes
5 replies
MichalOravec's avatar
Level 75
public function getDimensions(SearchDimensionRequest $request)
{
    $category = Category::whereHas('countries', function ($query) use ($request) {
        $query->where('countries.country_code', $request->selectedCountry);
    })->where('max_dimension', '>=', $request->dimension)
        ->orderBy('max_dimension')
        ->firstOrFail();

    $category->priceHtml = Cash::formatAmount($category->pivot->price);

    return $category;
}

I would use code instead of country_code in countries table. It's redundant.

For this line

$category->priceHtml = Cash::formatAmount($category->pivot->price);

I would use custom intermediate table model with accessor.

Docs: https://laravel.com/docs/8.x/eloquent-relationships#defining-custom-intermediate-table-models

MichalOravec's avatar

Ok so

public function getDimensions(SearchDimensionRequest $request)
{
    $category = Category::with(['countries' => $closure = function ($query) use ($request) {
        $query->where('countries.country_code', $request->selectedCountry);
    }])->whereHas('countries', $closure)->where('max_dimension', '>=', $request->dimension)
        ->orderBy('max_dimension')
        ->firstOrFail();

    $category->priceHtml = Cash::formatAmount($category->countries->first()->pivot->price);

    return $category;
}
Johny22's avatar

Ok So the best way would be to use your own middle table model with an access object and write it down as you mentioned in the first example?

Please or to participate in this conversation.