0

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?

1 Answer 1

3

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

    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Even thought this seems to be valid. You can use request() helper method. Laravel will resolve and save you for injecting in the class. so you validation will simply be 'field' => ['required', new CustomRule] and in your CustomRule class you use request('value'). Work as it should and less code
@usrNotFound thanks for this info, I didn't even know that myself

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.