我有一个数据库表,我们在其中存储所有用户的所有产品。
我们通过产品ID号获得产品页面,例如http://sitename.com/inventory/product/3
。
如果该产品不属于当前用户,如何拒绝通过URL访问该产品?
我有一个数据库表,我们在其中存储所有用户的所有产品。
我们通过产品ID号获得产品页面,例如http://sitename.com/inventory/product/3
。
如果该产品不属于当前用户,如何拒绝通过URL访问该产品?
Auth中间件可用于此目的。在路线功能中,您可以执行以下操作:
public function show($id){
//get the user visiting the route
$user = Auth::user();
//get the product by the id in the url
$product = Product::where('id','=',$id)->first();
if($user->id == $product->user_id){
//return the route like normal
}else{
//redirect or return route with different data
}
}
只需确保将use Auth;
添加到您的控制器即可。而且,您需要protect your route以确保只有经过身份验证的用户才能访问它。
为什么不只在控制器中使用firstOrFail()
?假设您的产品记录中包含一个指向所有者ID的created_by
,则您将同时按id
和created_by
进行搜索。如果未找到任何内容,则将引发404异常。
public function show(Request $request){
// Get the user-id
$user_id = Auth::user()->id;
// Get the product matching by id and owned by the current user
$product = Product::where('id',$request->id)->where('created_by',$user_id)->firstOrFail();
// Do your magic here if product found
}
https://laravel.com/docs/5.8/eloquent#retrieving-single-models