If you notice, you're doing two queries differently.
When you do this:
$users = DB::table('user')
->select('user.id','user.name', 'user.email')
->join('user_dep', 'user_dep.user_id', '=', 'user.id')
->where('user_dep.dep_id', '=',30)
->get();
you do it through Laravel Query Builder . This type of query results in a array
. That's why to access the attributes of each element you have to do as in any other array
:
.....
foreach($users as $user)
....
<td>{{ $user['name'] }}</td>
....
On the other hand, side when you consult like this:
$users = User::all();
You're using Eloquent . So the result is a collection of objects ( User
). This allows you to query the attributes as if they were methods (thanks to the 'magic' methods of PHP). That's why when you do the following you receive the data:
.....
foreach($users as $user)
....
<td>{{ $user->name }}</td>
....
Now, if what you want is to make your query through Eloquent, you have to do it through the relationships defined in your models.
By the name of your intermediate table ( user_dep
) I assume that you have a table / model Department
. In that model you can define the relationship in the following way:
app \ Department.php
// ...
public function users() // el método al que llamaremos
{
return $this->hasMany(User::class);
}
So your query would be the following:
$department = Department::find(30);
$users = $department->users;
// o de manera resumida:
// $users = Department::find(30)->users;
Allowing you to use these objects as you initially wanted them to:
.....
foreach($users as $user)
....
<td>{{ $user->name }}</td>
....