php - Join Table Values in Laravel Eloquent

I have an index() function on a controller that lists all of my users. Currently I can list all users, and values for the users but I can't get information from another table. Here is an an example of an SQL query I am trying to replicate in Eloquent.
SELECT user.id, user.name, user.email, user.title, timezones.name FROM users, timezones WHERE user.timezone=timezones.id
The way in which I currently display the users is:
$users = User::latest()->paginate(5); return view('users.index', compact('users'));
Table structure is as follows
Users Table:
id | name | email | timezone (int)
Timezone Table:
id | name
To output the data this is my index.blade.php file:
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->title }}</td>
<td>{{ $user->timezone }}</td>
</tr>
@endforeach
Answer
Solution:
One way to do this would be tojoin
thetimezones
table instead:
$users = User::select('user.id', 'user.name', 'user.email', 'user.title', 'timezones.name as timezone')
->join('timezones', 'user.timezone', 'timezones.id')
->latest()
->paginate(5);
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: use the option --with-all-dependencies (-w) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.