Correct way to run select query from blades in laravel 5 using eloquent
What is the correct way to get the column value based on a specific selection filter in the model variable used by the method compact
inside the blade. (Larev 5)
I read that its bad practice is to query the database from views from views, and so I followed the convention to take the required data with a compact
view method
However, in a scenario where I need to query another table based on a specific column value returned in a foreach loop inside the blade from the first table, I cannot find the right approach
Example: I have two models User
and a Group
Schematic User
Table
id,name,email,group_id
Scheme group table id
,groupname
Here is the UserController -> compact method
$users = \App\User::all(array('id','name','email','group_id'));
$groups = \App\Group::all(array('id','group_name'));
return view('user.index', compact('users','groups'));
Here like a blade needs them
@foreach ($users as $user)
<tr>
<th>{{$user->id}}</th>
<th>{{$user->name}}</th>
<th>{{$user->email}}</th>
<th>
<!-- Here i need to run something like
select group_name from group where id = $user->id -->
{{$groups->where('id','=',$user->group_id) }}
</th>
<th>Actions</th>
</tr>
@endforeach
I know this is returning an array and I have two questions here.
- How to get the value for a column
group_name
from a group-based group model.id
=$user->id
in foreach loop - Since its a bad practice to query the db from the blade, how would I use the values ββfrom the model, passing data through the compact from the controller to the blade when the where where is not known yet.
Edit 1:
I changed the last group request as
<th>@if($groups->where('id','=',$user->group_id))
@foreach($groups as $group)
{{$group->group_name}}
@endforeach
@endif
</th>
And I was able to get the result, however this is again not the correct approach, so the question remains unanswered
source to share
In the User
model
public function group()
{
return $this->belongsTo('App\Group');
}
In the Group
model
public function users()
{
return $this->hasMany('App\User');
}
In your controller
$users = \App\User::with('group')->get();
return view('user.index', compact('users'));
Now, in your opinion, you can do
$user->group->name;
source to share
I appreciate the fact that you know "It is bad practice to query from a view". Why don't you use join.
DB::table('users')->join('groups', 'users.group_id', '=', 'groups.id')->get();
Then convey the result to your mind and run through it. This is where you will have each user's data associated with their group data.
source to share