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


what correct way retrieve column value based on select filter on model variable availed compact method inside blade. (larevl 5)
read bad practice query database staright views, , hence followed convention avail required data compact method view

however, in scenario need query table based on column value returned in foreach loop inside blade first table, unable figure out correct approach

example: have 2 models user & group
schema user table

id,name,email,group_id 

scheme group table
id,groupname

here 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 blade needs them

@foreach ($users $user)       <tr>             <th>{{$user->id}}</th>             <th>{{$user->name}}</th>             <th>{{$user->email}}</th>             <th>               <!-- here need run  select group_name group id = $user->id --> {{$groups->where('id','=',$user->group_id) }}              </th>             <th>actions</th>         </tr>         @endforeach 

i know returns array , , i'have 2 questions here

  1. how value group_name column group model based on group.id = $user->id in foreach loop
  2. since bad practice query db blade, how avail values model passing data via compact controller blade, when clause parameter's not yet known.

edit 1:

i modified last group query

 <th>@if($groups->where('id','=',$user->group_id))                   @foreach($groups $group)       {{$group->group_name}}                               @endforeach                 @endif </th> 

and able result, again isn't correct approach , 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 controller

$users = \app\user::with('group')->get(); return view('user.index',  compact('users')); 

now in view can do

$user->group->name; 

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -