Duda laravel eloquent sql

2

I'm new to laravel and I have a couple of problems about eloquent .

I have the following code.

$usuario = 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();

I do not see any syntax error, but when I use a foreach to access the data in a table

.....
foreach($usuario as $us)
....
<td>{{$us->name}}</td>
....

The whole table appears blank. Any idea what I can do ?.

When I use $usuario = user::all(); I do not have problems accessing the information but now I need to segment it and I'm having problems.

    
asked by Erick López Martinez 25.06.2018 в 08:21
source

2 answers

1

Make sure that $ user is an object and not an arrangement. You can do it with:

var_dump($usuario);
die();

In case of being an arrangement you will have to use the cycle in the following way:

foreach($usuario[0] as $us)
{
    ...
}

Do not forget to validate that $ user is not null before placing your index.

Greetings.

    
answered by 25.06.2018 в 09:06
0

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>
....
    
answered by 02.07.2018 в 01:43