Laravel验证从列中获取值并将其与另一个表列进行比较

时间:2017-09-06 12:14:11

标签: php laravel relationship lumen laravel-validation

我有以下表格:

- 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。 我怎样才能做到这一点?

感谢。

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);