0
votes

I have users table assigned a foreign key(clinic_uuid, not primary key) to clinics table as below command.

$table->foreign('clinic_uuid',100)->references('clinic_uuid')->on('clinics');

After migration, I added 'hasmany users' relation to Clinic model.

public function users(){
 return $this->hasMany(User::class);
}

And also 'belongsTo Clinic' relation to User model

public function clinic(){
   return $this->belongsTo(Clinic::class,'clinic_uuid');
}

After that I add a few to clinics table.

    clinic_uuid       name
----------------------------------
       a1111       dog clinic
       a2222       cat clinic

And also users table.

  id    clinic_uuid       name
----------------------------------
  1       a1111           jame
  2       a1111           matt

Then, I try on my controller as below code but I get only null.

Auth::user()->clinic()->get();   --> get null
User::find(1)->clinic()->get();  --> get null

Appreciated for all advise.

2

2 Answers

0
votes

You will need to tell Eloquent what the local and foreign keys are for both relationships as neither of them follow the default convention:

public function clinic()
{
    return $this->belongsTo(Clinic::class, 'clinic_uuid', 'clinic_uuid');
}
public function users()
{
    return $this->hasMany(User::class, 'clinic_uuid', 'clinic_uuid');
}

Since the column names for both tables are the same it doesn't matter for this example but you can always refer to the docs to figure out which column name should go where in the relationship methods.

0
votes

Try with this,

User::with('clinic')->findOrFail(auth()->id());

Try to use eager loading Laravel Eager Loading

Hope this helps :)