John Davidson

php - Trying to add data for my many to many relationship

0 comments
Message:


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?



My Answer:
function to create the relationship, it creates a new guardian instead of using the existing one.

To solve this issue, you can modify your code to check if the guardian already exists in the database before creating a new one. Here's an example of how you can do this:

php
// Check if guardian already exists in the database
$existingGuardian = Guardian::where('name', $guardianName)->first();

if ($existingGuardian) {
// If guardian already exists, use the existing guardian
$student->guardians()->attach($existingGuardian->id);
} else {
// If guardian does not exist, create a new guardian
$newGuardian = new Guardian();
$newGuardian->name = $guardianName;
$newGuardian->save();

$student->guardians()->attach($newGuardian->id);
}


In this code snippet, we first check if a guardian with the given name already exists in the database. If it does, we use the existing guardian's ID to create the relationship with the student. If the guardian does not exist, we create a new guardian and then create the relationship with the student.

This way, you can ensure that you are not creating duplicate guardians in the database when creating relationships between students and guardians.

Rate this post

5 of 5 based on 5892 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us