5

How can I get all data from my tables with relationship in Laravel?

So, I have table like:

*users*
id
username
password
...

*address*
id
address
user_id
...

If I call my eloquent model with Address::all() I get response with user_id, and I want to make relationships for getting username.

I try to add:

public function users(){
  return $this->belongsTo('Users', 'user_id');
}

And call with Address::with('users')->get(), but response is empty.

Pavan
  • 17,840
  • 8
  • 59
  • 100
Kolesar
  • 1,265
  • 3
  • 19
  • 41

3 Answers3

6

Is your user class called Users or User? Unless you override it, the default way that Eloquent deals with names can be found in the docs (source):

Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a table property on your model

So I believe if you change your code in the Address model to:

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

it will work since we have changed Users to User

berrberr
  • 1,914
  • 11
  • 16
1

You need to change

public function users(){
   return $this->belongsTo('Users', 'user_id');
}

to

public function users(){
    return $this->hasOne(Users::class, 'user_id');
}

or

public function users(){
    return $this->hasMany(Users::class, 'user_id');
}
ZGski
  • 2,398
  • 1
  • 21
  • 34
LePepe
  • 53
  • 6
0

Alternative way!

 class Users extends Model {
   //override table
   protected $table = 'users';
   protected $primaryKey = 'id';
   //Your other code here
 }

and in Address Model add like this

 public function users(){
   return $this->belongsTo('App\Users', 'user_id');
 }
Bilal Maqsood
  • 1,163
  • 3
  • 15
  • 43