Relationship doesnt work in Laravel

752 views Asked by At

In my User model i have 2 relationships

 public function role()
{
    return $this->belongsTo(Role::class, 'role_id');
}

public function city()
{
    return $this->belongsTo(City::class, 'city_id');
}

The second City doesnt work when i use

$user = App\User::findorfail(1)->with('city')->first(); 

for example. It gives the message

Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [city] on model [App/User].

Class City is

<?php
 namespace App;

 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\SoftDeletes;


 class City extends Model
 {
 use SoftDeletes;

 protected $fillable = ['name', 'nomos_id','user_id'];
 protected $table = 'cities';


 public function setNomosIdAttribute($input)
 {
    $this->attributes['nomos_id'] = $input ? $input : null;
 }

 public function nomos()
 {
    return $this->belongsTo(Nomoi::class, 'nomos_id')->withTrashed();
 }

 }

What is the problem? Why one relationship works and the other doesnt.

2

There are 2 answers

3
Jerric Calosor On

Looking at the code $this->belongsTo(City::class, 'city_id') as an inverse of hasOne relationship that eventually would be looking at a city that the "user belongs to"?

Is this the intended purpose of this relation structure? If it is the inverse of it where as, we are looking for a city that "belongs to the user" we should be using $this->hasOne(City::class, 'city_id') of $this->hasMany(City::class, 'city_id') if it's a one-to-many relation.

2
Azeame On

with() calls should come before find(), first(), findOrFail, firstOrFail(), or get()

This should be all you need to eager load the City with the User.

$user = App\User::with('city')->findOrFail(1); 

But if you need to explicitly call first() on City then you should be using:

$user = App\User::with(['city'->function($query){ 
    return $query->first();
})->findOrFail(1);