Search code examples
phplaravelrelationshiphas-and-belongs-to-many

belongsTo() not returning relationships for User


I already tried several things but I can't get this to work. I want to be able to make something like this {{ $user->city->name }}

My user model:

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    public $timestamps = false;
    protected $table = 'users';
    protected $fillable = ['id_city', 'name', 'email', 'password', 'admin'];
    protected $hidden = ['password', 'remember_token'];

    public function city()
    {
        return $this->belongsTo('App\City');
    }
}

And this is my City model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class City extends Model
{
    public $timestamps = false;
    protected $table = 'cities';
    protected $fillable = ['name', 'slug'];

    public function users(){
        return $this->hasMany('App\User');
    }
}

And I'm trying to use {{ $user->city->name }} on my view but it doesn't work, it returns an error ErrorException: Trying to get property of non-object (View: .../views/app/text.blade.php).

What should I do?


Solution

  • Within your belongsTo relationship, Eloquent tries to match city_id as the foreign key by default as you don't pass the second argument.

    However, according to your fillable attributes, what you have as the foreign key is actually id_city.

    For the User model,

    public function city()
    {
        return $this->belongsTo('App\City', 'id_city');
    }
    

    For the City model,

    public function users(){
        return $this->hasMany('App\User', 'id_city', 'id');
    }