正在检索循环外的行


Retrieving a row outside loop

我在控制器中有这个功能:

   public function index()
      {
          $call=45;
          $show = DB::select('select * from users where position="keeper" ');
          return View('index',['users'=>$show,'call'=>$call]);  
     }

在视图中,我有一段代码:

  Call: {{$call}}    
  Position: {{$users->position}}     //what is the wrong with this line? everything is fine if i remove this line.
    @foreach ($users as $u)
    {{$u->id}}
    {{$u->name}}
    {{$u->email}} 
     @endif

错误:试图获取非对象的属性

同样适用于循环:

 @foreach($users as $r)
{{$r->position}}
@endforeach

您可以这样做。。

public function index()
  {
    $call=45;
    $show = DB::table('user')->where("position", "keeper")->first();
    return View('index',['user'=>$show,'call'=>$call]);   
 }

$show=DB::select('从用户中选择*,其中position="keeper"');

此查询返回多维对象。这就是为什么你不能像这个$user->position那样访问它的属性。

要解决这个问题,可以这样尝试:

public function index()
{
     $call=45;
     $show =  DB::select('select * from user where position = "keeper" limit 1')[0];
     return View('index', ['user' => $show, 'call' => $call]); 
}