Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent all with relationship

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.

like image 260
Kolesar Avatar asked Jan 13 '14 13:01

Kolesar


People also ask

How do you use eloquent relationships?

Using this Eloquent One-To-One relationship is very simple. Whenever you have an instance of the User model, you can call $user->profile or $user->profile()->chainOtherMethodsHere() . This is because $user is an instance of the User model, and right on that model we added a profile() method.

Does Laravel have many through relations?

Eloquent Relationships is one of the most useful and powerful features of the Laravel Framework. It is one of the reasons why I like Laravel most. Mainly it helps us to fetch or insert data in a very easy and efficient way.


1 Answers

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

like image 150
berrberr Avatar answered Oct 27 '22 06:10

berrberr