[英]Laravel 4.x, routing multiple related parameters
带有类似的链接
http://example.com/catalog/slug/brand/product
和类似的路线
Route::get('catalog/{slug}/{brand}/{product}', 'Controller@method');
并且知道每个参数都有一个绑定,该绑定检查该参数是否存在。
我有3张桌子:
Catalogs
id | catalog_slug
Brands
id | brand_slug
Products
id | product_slug | brand_id | catalog_id
如何检查那些参数是否相关(按产品表),而不是仅存在于路径中? 它工作正常,但我想确保它们彼此相关。
在您的方法中添加以下代码:
$parameters = Route::current()->parameters();
$areRelated = DB::table('Products')
->join('Brands','Brands.id','=','Products.brand_id')
->join('Catalogs','Catalogs.id','=','Products.catalog_id')
->where('Catalogs.catalog_slug',$parameters['slug'])
->where('Brands.brand_slug',$parameters['brand'])
->where('Products.product_slug',$parameters['product'])
->count();
if(! areRelated )
App::abort(404);
使用路由绑定 。
Route::get('catalog/{catalog}/{brandByID}/{productByID}', 'Controller@method');
在bindings.php中(在globals.php的末尾创建并包含)
Route::model('catalog', 'Catalog'); // now using {catalog} in route will look up the catalog instance by ID and pass it to the controller method instead of the ID.
// use custom resolver for brand parameter, use {brandByID} in route
Route::bind('brandByID', function ($brandID, $route) {
//Get the catalog from the catalog bind function
$catalog = $route->parameter('catalog');
$brand = $catalog->brands()->findOrFail($brandID); // fails if catalog does not have this brand
return $brand;
}
对产品执行相同的操作,但添加第二项检查。 您还需要在目录模型中正确设置品牌关系,例如
public function brands()
{
return $this->belongsToMany('Brand');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.