Lijesh Shakya
Lijesh Shakya

Reputation: 2540

Laravel Rule: Custom Validation Depending Upon Two Request Inputs

I want to validate if the user is associated with the order in the request validation.

Order Migration:

$table->bigIncrements('id');

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

...

$table->timestamps();

$table->softDeletes();

User Table:

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

I have manually created a function to check if the order is associated with the user

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

    return $checkExistsStatus;
}

When I need to check the associate, I have to call this function like:

$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{
    ...
}

I tried to create a new rule: CheckAssociationBetweenOrderAndUser but I am unable to pass the user_id to it.

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

Is there any better way to validate the association check by creating a custom new rule? Or this is the only way to check the association?

Upvotes: 0

Views: 197

Answers (1)

julianstark999
julianstark999

Reputation: 3616

Creating a custom rule was a good attempt. You can pass the $request as param in the constructor like

$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;
    }

    ...
}

Upvotes: 3

Related Questions