mardi 15 novembre 2016

Laravel How can I save a 1:many relationship?

I am using Laravel 5.3 and I am trying to save a 1:many relationship that is coming in from post data.

I have the relationships set up and they are working correctly when I read the objects, but I haven't figured out how to actually save them. (hard coding up to this point).

...
$data = new Student;
$data->fill($request->all());

$student = Student::find($request->id); // get the id of the newly created student

foreach ($request->activities as $activity) {
    $student->activities()->save([
        'student_id' => $request->id,
        'activity_id' => $activity,
    ]);
}

The error I am getting is:

 Call to a member function activities() on null 

activities is coming across in my post data as an array.

activities[
    [0] => 1
    [0] => 2
     ...
]

The value(s) of each key are the id's of the activity.

Activity

public function students()
{
    return $this->belongsToMany('App\Student');
}

Student

public function activities()
{
    return $this->belongsToMany('App\Activity');
}

I think this part from the docs is what I need, but I'm just not following along.

Any suggestions are appreciated!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire