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;
}
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
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;
}
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 sign in or create an account to participate in this conversation.