【问题标题】:Error "Call to undefined method Illuminate\Auth\GenericUser" when accessing to hasMany relationship of Auth::user()访问 Auth::user() 的 hasMany 关系时出现错误“调用未定义的方法 Illuminate\Auth\GenericUser”
【发布时间】:2016-04-26 16:36:04
【问题描述】:

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

调用未定义的方法 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');
}

此时我真的不知道出了什么问题,但是当我从 tinker 创建新的患者记录时,它按预期工作:

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

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

有人能找出错误在哪里吗?

【问题讨论】:

    标签: authentication laravel-5


    【解决方案1】:

    我发现了问题所在,我在 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',
            // ],
    ],
    

    【讨论】:

      猜你喜欢
      • 2020-04-07
      • 1970-01-01
      • 2017-11-06
      • 2020-01-24
      • 2020-02-26
      • 1970-01-01
      • 2020-07-16
      • 1970-01-01
      • 2022-11-03
      相关资源
      最近更新 更多