Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to run a select query from blades in laravel 5 using eloquent

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 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 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

  1. How to get the value for group_name column from the Group Model based on group.id = $user->id in a foreach loop
  2. Since Its a bad practice to query db from blade, how would I avail the values from a model by passing data via compact from controller to blade, when the where clause parameter's are not yet known.

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

like image 736
echoashu Avatar asked Dec 24 '22 18:12

echoashu


1 Answers

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;
like image 75
chanafdo Avatar answered Dec 28 '22 08:12

chanafdo