Home > Blockchain >  Howto reusing Form Request inside loop
Howto reusing Form Request inside loop

Time:11-25

I am making a "/bulk" endpoint for my API/REST made in Laravel 8. My problem is that I don't know how to reuse the same FormRequest that I have for the create or update

json post to: /cars/bulk

{
"cars": [{"model": "A", "year": 2021, "plate": "AA11BB"},{"model": "B", "year": 2021, "plate": "AA12BB"},{"model": "C", "plate": "AA13BB"}]
}
// CarController.php
public function store(CarRequest $request)
{
    $car = $this->carService->store($request, Car::class);
}

public function update(CarRequest $request, Car $car)
{
    $this->carService->update($request, $car);
}

public function bulk(Request $request)
{
    $this->carService->bulk($request);
}
// CarService.php
public function store($request, $modelClass)
{
    # My code....
}

public function update($request, $model)
{
    # My code....
}

public function bulk($request)
{
    foreach ($request->cars AS $carData )
    {
        $car = Car::where('plate','=',$carData->plate)->first()

        # here is the problem, 
        # howto validate each $car by reusing CarRequest

        if ($car){
            $this->update($carData, $car);
        } else {
            $this->store($carData, Car::class);
        }


    }
}

This is de form request for each item, i have use to for bulk or one request

class CarRequest extends BaseRequest
{


    public function authorize()
    {

        $this->setModel(Car::class);
        return $this->isAuthorized();
    }


    public function rules()
    {
        $this->setModel(Car::class);
        $rules = parent::rules();

        $rules = [
            'model' => 'required',
            'year'  => 'required|numeric',
            'plate' => 'required'
        ];

        return $rules;
    }

    public function messages()
    {
        # multiples messages
    }
}

I need reuse my request

Edit: add form request

CodePudding user response:

So I wouldn't suggest using it within a loop how you have in your example, what would be better would be to create a second, bulk request that valiates an array like this.

public function rules()
    {
        $this->setModel(Car::class);
        $rules = parent::rules();

        $rules = [
            'cars' => ['required', 'array'],
            'cars.*.model' => 'required',
            'cars.*.year'  => 'required|numeric',
            'cars.*.plate' => 'required'
        ];

        return $rules;
    }

CodePudding user response:

You can do it with same CarRequest form request class as follows.

public function rules()
{
    return[
        'cars.*.model' => 'required',
        'cars.*.year' => 'required',
        'cars.*.plate' => 'required',
    ];

}

Laravel will expect that you are sending nested array. If you dont want to mix it up with CarRequest you can do it with creating another FormRequest class.

  • Related