【问题标题】:Laravel Rule: Custom Validation Depending Upon Two Request InputsLaravel 规则:基于两个请求输入的自定义验证
【发布时间】:2020-03-11 05:45:03
【问题描述】:

我想在请求验证中验证用户是否与订单相关联。

订单迁移:

$table->bigIncrements('id');

$table->unsignedBigInteger('user_id')->nullable();

...

$table->timestamps();

$table->softDeletes();

用户表:

$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamps();

我手动创建了一个函数来检查订单是否与用户关联

public function checkIfOrderIsAssociatedWithTheUser(Request $request){
     $checkExistsStatus = Order::where('id',$request->order_id)->where('user_id', $request->user_id)->exists();

    return $checkExistsStatus;
}

当我需要检查关联时,我必须像这样调用这个函数:

$this->validate($request, [
    'order_id' => 'required|exists:orders,id',
    'user_id' => 'required|exists:users,id'
]);

$checkExistsStatus = $this->checkIfOrderIsAssociatedWithTheUser($request);

if(!$checkExistsStatus){
    return redirect()->back()->withErrors([
        'Order and user is not linked'
    ]);
}else{
    ...
}

我尝试创建一个新规则:CheckAssociationBetweenOrderAndUser,但我无法将 user_id 传递给它。

$this->validate($request, [
    //unable to pass user_id
    'order_id' => ['required', new CheckAssociationBetweenOrderAndUser()]
]);

有没有更好的方法通过创建自定义新规则来验证关联检查?或者这是检查关联的唯一方法?

【问题讨论】:

    标签: php laravel laravel-5 laravel-5.7 laravel-validation


    【解决方案1】:

    创建自定义规则是一个很好的尝试。您可以在构造函数中将$request 作为参数传递,例如

    $this->validate($request, [
        'field' => ['required', new CustomRule ($request)]
    ]);
    
    namespace App\Rules;
    
    use Illuminate\Contracts\Validation\Rule;
    use Illuminate\Http\Request;
    
    class CustomRule implements Rule
    {
        protected $request;
    
        public function __construct(Request $request)
        {
            $this->request = $request;
        }
    
        ...
    }
    

    【讨论】:

    • 甚至认为这似乎是有效的。您可以使用request() 辅助方法。 Laravel 将解析并保存你在课堂上注入。所以你的验证只是'field' => ['required', new CustomRule],在你的CustomRule类中你使用request('value')。工作正常,代码更少
    • @usrNotFound 谢谢你的信息,我自己都不知道
    猜你喜欢
    • 2017-12-06
    • 2021-06-24
    • 2017-04-11
    • 2018-02-18
    • 2018-06-03
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-07-03
    相关资源
    最近更新 更多