0

I have a form in Laravel blade and I am having trouble with validating data. I validated data from my controller with $request->validate(['some_data' => 'some_value']) as an example. I put that in variable $validatedData and I use that variable bellow in session put method and in fill method and it worked fine. What I did is tried to refactor code and I put that validation in FormRequest and removed variable $validatedData and put $request instead of it. When I did that then it showed an error

Argument 1 passed to Illuminate\Database\Eloquent\Model::fill() must be of the type array, object given

and it breaks down because now $request now isn't an array like it was before, it is an object instead. How should I fix that to work? Any help is appreciated. Here is my code.

Controller

public function postStepOne(FirstFormRequest $request)
{
    // $validatedData = $request->validate(['some_data' => 'some_value', etc.]);

    if(empty($request->session()->get('questionnaire'))){
        $questionnaire = new Questionnaire();
        $questionnaire->fill($request); IT WAS $validatedData BEFORE
        $request->session()->put('questionnaire', $questionnaire);
    } else {
        $questionnaire = $request->session()->get('questionnaire');
        $questionnaire->fill($request); // IT WAS $validatedData BEFORE
        $questionnaire->session()->put('questionnaire', $questionnaire);
    }

    return redirect()->route('questionnaires.create.step.two');
}

FirstFormRequest

public function rules()
{
    return [
      'business' => 'required',
      'residing' => 'required|in:yes,no',
      'different_address' => 'required_if:residing,yes',
      'business_address' => 'required_if:different_address,no',
      'company_name' => 'required|string|max:255',
    ];
}
Orion
  • 248
  • 3
  • 10
mrmar
  • 1,407
  • 3
  • 11
  • 26

1 Answers1

2

You can get the validated inputs from the Form Request with the validated method:

$questionnaire->fill($request->validated());

You can do the initialization and filling in one statement though:

$questionnaire = new Questionnaire($request->validated());
lagbox
  • 48,571
  • 8
  • 72
  • 83
  • Yes, that's it it works, thank you! Only one more thing regarding one statment initialization and filling that you wrote. Can I call new Questionnaire class with just 'new self'? – mrmar Nov 27 '20 at 14:51
  • 1
    if you were in the context of the Model class yes, but you are doing this from a Controller (outside the model) – lagbox Nov 27 '20 at 14:56
  • Yes, I do it from controller but I call in construct method QuestionnaireRepository which calls Questionnaire model – mrmar Nov 27 '20 at 14:58