Home > other >  How can I bypass a FormRequest validation in Laravel to store a user_id?
How can I bypass a FormRequest validation in Laravel to store a user_id?

Time:11-20

I'm building an API and I need to store a Customer. When the customer is stored, automatically, a User is created. The User created belongs to a Customer, and a Customer needs to store in his database the user_id previously created.

I have the following code where I use the FormRequest to store a new Customer. I use a DB Transaction to ensure the safeness of the operation. After I store the User, I use his id to associate to the field user_id in the Customer request.

public function store(StoreCustomerRequest $request)
{
    /* --- DB Transaction -> Create User   Customer --- */
    DB::transaction(function () use ($request) {
        // -> Creates User
        $create_user = (new UserController)->store($request);

        // -> Creates Customer
        $request->merge(['user_id' => $create_user->id]);
        $customer = Customer::create($request->validated());

        return new CustomerResource($customer);
    });
}

The StoreCustomerRequest has the following rules.

public function rules()
{
    return [
        'user_id' => 'required|integer|exists:users,id',
        'phone' => 'required|min:0|max:20',
        'points' => 'required|min:0',
        'nif' => 'nullable|digits:9',
        'default_payment_type' => 'nullable|in:VISA,PAYPAL,MBWAY',
        'default_payment_reference' => 'nullable',
        'custom' => 'nullable'
    ];
}

When I try to store a new Customer, the field user_id goes null (because there is no user to associate with). Therefore, there is an error saying "The user id field is required.".

The question is: How can I bypass this validation and store the customer with the user_id previously created?

I have already tried to change the rules in the StoreCustomerRequest and make the user_id nullable, but when I try to store it, it says that the user cannot be null.

CodePudding user response:

There is a rule in laravel called sometimes which only validates if a field is present. You can use that in the rules like so.

public function rules()
{
    return [
        'user_id' => 'sometimes|integer|exists:users,id'
    ];
}
  • Related