访问Auth :: user()的hasMany关系时出错“调用未定义的方法Illuminate \ Auth \ GenericUser”

时间:2016-04-26 16:36:04

标签: authentication laravel-5

我在用户和患者之间定义了一对多的关系,但是当我尝试使用经过身份验证的用户保存新的患者记录时,我收到了错误

  

调用未定义的方法Illuminate \ Auth \ GenericUser :: patients()

以下是我的表格:

// 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');
});

在PatientController中,我调用Auth :: user()来保存新患者:

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!');
}

关系定义如下:

// IN USER MODEL
public function patients(){
    return $this->hasMany('App\Patient');
}

// IN PATIENT MODEL
public function user(){
    return $this->belongsTo('App\User');
}

此时我真的不知道出了什么问题,但是当我从修补程序创建一个新的病历时,它按预期工作:

>>> $patient = new App\Patient;
>>> $patient->ci = "1234567";
.......
.......

>>> $user = App\User::first();
>>> $user->patients()->save($patient);

有人可以找出错误在哪里吗?

1 个答案:

答案 0 :(得分:0)

我发现问题是什么,我在auth.php文件中的providers数组中保留了未注释的两个选项:

'providers' => [
        'users' => [
                'driver' => 'eloquent',
                'model' => App\User::class,
        ],

        // ERROR
        // Call to undefined method Illuminate\Auth\GenericUser::patients()

        // 'users' => [
                //'driver' => 'database',
                //'table' => 'users',
        // ],
],