Answer the question
In order to leave comments, you need to log in
How to properly build a query (Laravel)?
Good day everyone! And good mood!
There was a question on the correct construction of request
There is a table with regions:
Table name `regions`
`region_id` (int);
`region_name`(varchar);
`region_code`(int);
Table with categories:
Table name `categories`
`cat_id` (int);
`cat_name`(varchar);
Table with goods:
Table name `goods`
`good_id` (int);
`good_name`(varchar);
`good_region`(int);
`good_cat`(int);
I want to make the link look like this site.ru/moskow/audio/2452145
in route.php I write a route like this:
Route::get('/{region}/{category}/{id}','[email protected]');
public function show($region, $category, $id){
//тут у меня тупик
}
Answer the question
In order to leave comments, you need to log in
It is assumed that the links are configured correctly.
And don't forget the indexes on the fields cat_name, region_name.
Link to documentation .
$result = Goods::query()
->whereHas('category', function ($query) use ($category) {
/** @var \Illuminate\Database\Query\Builder $query */
$query->where('cat_name', $category);
})
->whereHas('region', function ($query) use ($region) {
/** @var \Illuminate\Database\Query\Builder $query */
$query->where('region_name', $region);
})
->where('id', $id)
->with('category', 'region')
->first(); // можно ->firstOrFail() = само выкинет ошибку
if ($result === null) {
// 404
}
First, make connections in the models. So it will be easier.
public function show($region, $category, $id){
$Region = Region::where('region_code', '=', $region)->first();
$Category = Category::where('cat_name', '=', $category)->first();
$Region->products()->where('good_region', $Region->id)->where('good_cat', '=', $Category->id)->where('id', '=', $id)->first();
return view(...)
}
You can bind models in routes.
Route::model('region', \App\Models\Region::class);
Route::model('category', \App\Models\Category::class);
Route::model('good', \App\Models\Good::class);
Route::get('/{region}/{category}/{good}', '[email protected]');
public function show(Region $region, Category $category, Good $good){
//
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question