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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With