What is the Correct Way to retrieve a column value based on certain select filter on a Model variable availed by compact
method inside the blade. (Larevl 5)
I read that Its a bad practice to query database staright from views, and hence i followed the convention to avail the required data with compact
method to view
However, In a scenario where I need to query another table based on certain column value returned in foreach loop inside a blade from first table, I am unable to figure out correct Approach
Example: I have two Models User
& Group
Schema User
Table
id,name,email,group_id
Scheme Group Tableid
,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 how the 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 returns an array , and I'have two questions here
group_name
column from the Group Model based on group.id
= $user->id
in a foreach loop Edit 1:
I modified the last group query 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 again isn't a correct approach , so question remain unanswered
In User
model
public function group()
{
return $this->belongsTo('App\Group');
}
In 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 view you can do
$user->group->name;
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