早上好
我试图用多个变量创建一个过滤器,例如,我想按类别(例如“水果”)过滤我的产品,然后我想按标签(例如“ sale”)过滤产品,因此我得到了所有我正在出售的水果。我设法在laravel中为类别和标签编写了单独的过滤器,但是如果我在我的productsController中将它们都保留为活动状态,则它们会相互抵触。我想我必须用if / else-statement编写一个函数,但是我不知道从哪里开始。有人可以帮我吗?
这些是我的productsController中的函数:
public function productsPerTag($id){
$tags = Tag::all();
$products = Product::with(['category','tag','photo'])->where(['tag_id','category_id'] ,'=', $id)->get();
return view('admin.products.index',compact('products','tags'));
}
public function productsPerCategory($id){
$categories = Category::all(); //om het speciefieke id op te vangen heb ik alle categories nodig
$products = Product::with(['category','tag','photo'])->where('category_id', '=', $id)->get();
return view('admin.products.index',compact('products','categories'));
}
这些是我在web.php中的路线。我想这也必须改变:
Route::get('admin/products/tag/{id}','AdminProductsController@productsPerTag')->name('admin.productsPerTag');
路线:: get('admin / products / category / {id}','AdminProductsController @ productsPerCategory')-> name('admin.productsPerCategory');
您正在尝试过滤查询,但仅将1个参数传递给控制器,该参数不起作用。
1)您需要将过滤器添加为URL中的查询参数,因此您的URL如下所示:
Query parameters are NOT to be put in the
web.php
. You use them like above when you use the URL and are optional.2)更改您的控制器以接受过滤器:
Keep in mind that while
{id}
is a$request->route()->parameter('id')
the query parameters are handled as
$request->input('category_id')
to retrieve them in controller.这可能会有所帮助,但可能并非出于您的目的。
合并或加入模型,然后在前端进行过滤。