I defined a relationship One-to-Many between User and Patient, but when I try to save a new patient record with the authenticated user I get the error
Call to undefined method Illuminate\Auth\GenericUser::patients()
Here are my tables:
// Users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
// Patients table
Schema::create('patients', function (Blueprint $table) {
$table->increments('id');
//Foreign key
$table->integer('user_id')->unsigned();
$table->string('ci')->unique();
$table->string('name');
$table->string('last_name');
$table->string('gender');
$table->date('birth_date')->nullable();
$table->string('place')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')
->references('id')->on('users');
});
In PatientController I call Auth::user() to save a new patient:
public function store(PatientRequest $request){
$patient = new Patient($request->all());
Auth::user()->patients()->save($patient);
$last = Patient::get()->last();
return redirect()->route('patient.histories.create', [$last->id])->with('message', 'Success!');
}
And the relationships are defined as follows:
// IN USER MODEL
public function patients(){
return $this->hasMany('App\Patient');
}
// IN PATIENT MODEL
public function user(){
return $this->belongsTo('App\User');
}
At this point I really don't know what is wrong, but when I create a new patient record from tinker it works as expected:
>>> $patient = new App\Patient;
>>> $patient->ci = "1234567";
.......
.......
>>> $user = App\User::first();
>>> $user->patients()->save($patient);
Can someone spot where is the error, please?
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire