Home > Software engineering >  Trying to add data for my many to many relationship
Trying to add data for my many to many relationship

Time:09-06

I have a pivot table where I store Student and guardian relationships, I create student first before adding guardian Cause Student and guardian have two tables and I relate to them using ids. When I create a new Guardian everything works fine but the problem is when I try to merge an old guardian with a new student and I call my model "getStudent" i get the error "Call to a member function getStudent() on string"

//Guardians Model

 public function getStudent()
{
    return $this->belongsToMany(Student::class);
}

//Student Model

public function Guardians()
    {
        return $this->belongsToMany(Guardian::class);
    }

//Controller

if (isset($_POST['merge'])) {
                $student = Student::find($id);
                $guardian =  $req->input('parent_id');
                dd($guardian->getStudent()->attach($student->id));
            }

I am able to get the two Id but how do I save without errors to my pivot?

CodePudding user response:

your calling getStudent() function from a request Object you can call this function form a Guardian modal instance so

you code should look like

if (isset($_POST['merge'])) {
    $student = Student::find($id);
    $guardian =  Guardian::find($req->input('parent_id'));
    dd($guardian->getStudent()->attach($student->id));
}

CodePudding user response:

You should do like this:

if (isset($_POST['merge'])) {

    // $student = Student::find($id);

    $guardian = Guardian::find($req->input('parent_id'));
    $guardian->getStudent()->attach($id);
}
  • Related