Mawunyo
1 month ago
108
1
Laravel

Many to many relationship

Posted 1 month ago by Mawunyo

Hi I want to check if Patient already exist insert only doctor_patient with many to may relationship

This is my code but I get "Undefined variable: patient" error in the else condition .

How Can I fixed that.

public function store(Request $request)
{
    $password = Str::random(6);

    $this->validate($request,[
        'firstname' => 'required|string|max:255',
        'lastname' => 'required|string|max:255',
        'phone' => 'required',
    ]);

    $ready_patient = Patient::where('phone', '=', $request['phone'])
                                ->first();

    if($ready_patient === null){
        $patient =  Patient::create([
        'firstname' => $request['firstname'],
        'lastname' => $request['lastname'],
        'email' => $request['email'],
        'phone' => $request['phone'],
        'sexe' => $request['sexe'],
        'password' => Hash::make($password),
    ]);

        $doctor = auth('doctor')->user();

        $patient->doctors()->attach($doctor);

    }else{

        $doctor = auth('doctor')->user();

        $patient->doctors()->attach($doctor);
    }

    return $patient;
}

Please sign in or create an account to participate in this conversation.