Laravel 规则:自定义验证取决于两个请求输入
Laravel Rule: Custom Validation Depending Upon Two Request Inputs
我想验证用户是否与请求验证中的订单相关联。
订单迁移:
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->nullable();
...
$table->timestamps();
$table->softDeletes();
用户Table:
$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()]
]);
是否有更好的方法通过创建自定义新规则来验证关联检查?或者这是检查关联的唯一方法?
创建自定义规则是一次不错的尝试。您可以在构造函数中将 $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;
}
...
}
我想验证用户是否与请求验证中的订单相关联。
订单迁移:
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id')->nullable();
...
$table->timestamps();
$table->softDeletes();
用户Table:
$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()]
]);
是否有更好的方法通过创建自定义新规则来验证关联检查?或者这是检查关联的唯一方法?
创建自定义规则是一次不错的尝试。您可以在构造函数中将 $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;
}
...
}