A very casual question with the multi level DB tables and eloquent query system.
A MainCategory has more than one Category(
categoriestable)A Category has more than one Product(
productstable)
Now the routes.php has:
Route::get('/categories/{slug}', ['as' => 'categories.list', 'uses' => 'ListController@getCategories'])->where('slug', '[\w\d\-\_]+');
The ListController@getCategories method wants to list all products along with the categories come under the main_category.
class ListController extends Controller
{
public function getCategories($slug) {
$categories = Category::orderBy('id', 'asc')
->select('categories.id as cat_id', 'categories.name as cat_name','categories.slug as cat_slug','products.*')
->join('main_categories', 'main_categories.id', '=', 'categories.main_category_id')
->join('products', 'products.category_id', '=', 'categories.id')
->where('main_categories.slug', '=', $slug)
->get();
if(count($categories) > 0) {
return view('pages.categories')->withCategories($categories);
}
else { // either main_categories.name not in $slug or there is no category available for this main_category
}
}
}
The code works fine as expected, listing both products and categories from the same collection object.
Now there is an else case. How could I check the result collection so that I can differentiate if there was a main_category in the name of given $slug or if there was no categories under the main_category with $slug.
See the code, count($categories) returns 0 for both cases. I don't stick on my eloquent way. You may suggest me another query or a condition check with PHP. I would like to know the best efficient way to do this.
[PS:All relations are direct and pretty basic(belongsTo and hasMany) and table names are in common standard- the Laravel 5 way of dooing it(using v5.2) so I guess you get if there is a code needed/missing in my question.]
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire