jeesoon
jeesoon

Reputation: 467

Relationship returning NULL

Im very new to Laravel. I want to display the data i needed and i create a relationship to my tables but its not working. Can you find any of my mistakes?

i have two tables Users and Places

Users Model

protected $fillable = array('name', 'email', 'password','role','places_id');

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

Places Model

protected $fillable = array('name','email','phone','address','bio');

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

Controller

 $users = User::with('Places')->get();
 return view('/dashboard')->with('users',$users);

The output is

Collection {#121 ▼
  #items: array:3 [▼
    0 => User {#322 ▶}
    1 => User {#323 ▶}
    2 => User {#324 ▼
      #fillable: array:5 [▶]
      #hidden: array:2 [▶]
      #connection: "mysql"
      #table: "users"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▶]
      #original: array:10 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "Places" => null
      ]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
  ]
}

Upvotes: 2

Views: 532

Answers (1)

Virginia
Virginia

Reputation: 737

I think you have your relations swapped. It is the other way around:

Users model:

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

A User has the foreign key places_id, so a User does not belong to a place, but has a place.

Places model:

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

A Place does not have a user, but instead belongs to a User. I know it is confusing in the beginning, but you'll surely get the hang of it! You can use this 'trick' to help you (at least that's how I remember it all the time):

Name of Model 'relationship' name of function


Addition / update after new comment of original poster (with foreign keys):

Users model:

public function places()
{
     return $this->hasMany('App\Places', 'places_id', 'id');
}

Places model:

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

The format for a relationship is ('Model Name', 'foreign key', 'local key').

Upvotes: 4

Related Questions