【问题标题】:Laravel validation get value from a column and compare it to another table columnLaravel 验证从列中获取值并将其与另一个表列进行比较
【发布时间】:2018-02-14 22:17:48
【问题描述】:

我有以下表格:

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

谢谢。

【问题讨论】:

    标签: php laravel relationship lumen laravel-validation


    【解决方案1】:

    你可以在 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);
    

    【讨论】:

      【解决方案2】:

      最容易监督的方式是写custom validator

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-09-05
        • 1970-01-01
        • 2021-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多