Laravel:验证一个字段是否对应于特定的行

Laravel: Validate that a field corresponds to a specific row

我正在使用护照为我的 API 构建注册方法。当用户进行注册时,我想 return 他访问令牌,类似于我们请求访问令牌时的情况。为此 '使用授予密码客户端。

我所做的是在注册数据中询问client_id沿client_secret

那么我正在寻找的是我的验证规则能够验证 client_secret 对应于 client_id.

这是我的注册方式:

/**
 * Register a new user in the system.
 * @param \Illuminate\Http\Request $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $vb = User::ValidationBook();
    $data = $request->validate($vb["rules"], $vb["messages"]);

    // Neccesary data to get a token at registration
    $password = $data["user"]["password"];
    $clientId = $data["user"]["client_id"];
    $clientSecret = $data["user"]["client_secret"];

    // If validation passes, create user
    $user = $this->userService->store($data);

    $request->request->add([
        'grant_type'    => 'password',
        'client_id'     => $clientId,
        'client_secret' => $clientSecret,
        'username'      => $user->email,
        'password'      => $password,
        'scope'         => null,
    ]);

    // Fire off the internal request.
    $token = Request::create(
        'oauth/token',
        'POST'
    );
    return \Route::dispatch($token);

}

这里是我的用户模型的简化版本,我在验证书方法中有所有规则。

class User extends Authenticatable
{
    /**
     * Returns an array that contains two indexes:
     * 'rules' for the validation
     * 'messages' messages given by the validation
     *
     * @return array
     **/
    public static function ValidationBook($except = [], $append = [])
    {
        $book = ['rules' => [], 'messages' => []];
        $book['rules'] = [
            ... the other rules
            //Extra data for register
            'user.client_id' => 'required|exists:oauth_clients,id',
            'user.client_secret' => 'required|exists:oauth_clients,secret'
        ];
        $book['messages'] = [
            ... the other messages
            // Extras
            'user.client_id.required' => 'The client id is required',
            'user.client_secret.required' => 'The client secret is required',
        ];
        if (!empty($except)) {
            $except = array_flip($except);
            $book['rules'] = array_diff_key($book['rules'], $except);
        }
        if (!empty($append)) {
            $book = array_merge_recursive($book, $append);
        }
        return $book;
    }

}

我如何向 user.client_secret 规则添加一条规则来验证该机密是否对应于该特定 ID? 这可能不是注册后 return 访问令牌的最佳选择,如果有一种简单的方法可以避免它,我将很高兴了解它。

提前致谢。

解决方法很简单。在我的验证规则中,在 user.client_secret 上,我添加了以下值:

$book['rules'] = [
    ... the other rules
    'user.client_id' => 'required|exists:oauth_clients,id',
    'user.client_secret' => 'required|exists:oauth_clients,secret,id,'
];

在此,在验证秘密是否存在的旁边,我添加了查询以检查具有指定 ID 的所有记录。

然后在验证之前,我将所需的 id 添加到规则中:

$vb = User::ValidationBook();
$vb["rules"]["user.client_secret"] .= $request->input("user")["client_id"];
$data = $request->validate($vb["rules"], $vb["messages"]);