我有以下表格:
- companies
- users
- departments
- services
我们有以下结构:
A user belongs to a company
A company has many departments
One department has multiple services.
问题是我想仅使用服务ID验证具有特定company_id
标志的服务部门。
数据库:
公司
| id | name |
| 1 | Company 1 |
| 2 | Company 2 |
用户
| id | name | company_id |
| 1 | User 1 | 1 |
部门
| id | name | company_id |
| 1 | Department 1 | 1 |
| 2 | Department 2 | 2 |
服务
| id | name | departments_id |
| 1 | Service 1 | 1 |
| 2 | Service 2 | 2 |
端点如下所示:
用户归属于Company 1
$app->delete('/{id}', ['uses' => 'ServicesController@deleteService']);
删除服务方法
public function deleteService($id, Request $request)
{
$request['id'] = $id;
$this->validate($request, [
'id' => 'required|exists:services,id',
]);
$result = Service::deleteService($id, $this->user->company_id);
return response()->json($result);
}
Company 1
的用户无法删除Service 2
。
我怎样才能做到这一点?
感谢。
答案 0 :(得分:0)
最可观的方式是写一个custom validator
答案 1 :(得分:0)
您可以在Laravel中使用policies
执行此操作,请查看docs
它将是这样的
$request['id'] = $id;
$this->validate($request, [
'id' => 'required|exists:services,id',
]);
$this->authorize('delete', $id); // will check if user can delete the company as the needed logic.
$result = Service::deleteService($id, $this->user->company_id);
return response()->json($result);