0

I have a dynamic input field called name="step[]". When submitting the form and displaying the $request->step using dd, I get this:

array:3 [
  0 => "Test Step 1"
  1 => "Test Step 2"
  2 => "Test Step 3"
]

So it is an array. Now, when I want to insert the data using:

    $project = new Project;

    $project->name = $request->name;

    $project->save();

    $project->steps()->saveMany($request->step);

I am getting this error:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given

Project Model:

public function steps()
{
    return $this->hasMany('App\Step');
}

My goal is to create a new Project and save it to the database, and save all steps in my Step table. So each Project hasMany steps. Not sure why I am getting the above error though, since I am passing an array?

1
  • 1
    An array yes. An array of models, no. $project->steps()->saveMany( /** array of models expected */). Commented Feb 23, 2016 at 15:45

2 Answers 2

1

I usually realize using a foreach loop. Your relation method seems to look OK. Does this work?

foreach($request->steps as $step) {
  $project->steps()->create(['step' => $step]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works in the meanwhile :) I wanted to do something without using a foreach, but since David Barker pointed out to me why I am getting the error, I can work on achieving what I want :)
0

Did you try using the attach method?

$project->steps()->attach($resquest->input('steps'));

Comments

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.