PHP laravel 未定义变量:控制器中的用户 ID


PHP laravel Undefined variable: userid in controllers

这是我的sql查询

select * from users us join EmailBox em on us.userid = em.suserid 
where em.status = "Delete" and (em.suserid="$userid" or em.riemailid="$user")

我想检查任何一个字段,如果只有"suserid"或"riemailid"结果。所以我在 laravel 查询生成器中更改了它。

$lists = EmailBox::join('users as us', 'EmailBox.suserid', '=', 'us.id')
                ->where('status' , 'Delete')
                ->where(function($query){
                 $query->where('suserid' , '$userid');
                 $query->orwhere('riemailid' , '$user');    
        })->paginate(5);

当值将被直接传递时,此查询工作正常, 用户 ID 直接传递 1 表示

$lists = EmailBox::join('users as us', 'EmailBox.suserid', '=', 'us.id')
                    ->where('status' , 'Delete')
                    ->where(function($query){
                    $query->where('suserid' , 1);
                    $query->orwhere('riemailid' , '$user'); 
        })->paginate(5);

这是我在 laravel 中的代码。什么是错误?

    if(Auth::check()){
        //if(Auth::user()->email!="")
        $user=Auth::user()->email;
        $userid=Auth::user()->id;
        $lists = EmailBox::join('users as us', 'EmailBox.suserid', '=', 'us.id')
                            ->where('status' , 'Delete')
                            ->where(function($query){
                                $query->where('suserid' , '$userid');
                                $query->orwhere('riemailid' , '$user'); 
                            })->paginate(5);
        $links = $lists->render();
        return view('front.index', compact('lists', 'links'));
    }

我收到错误$userid变量未定义。

->where(function($query) use($userid, $user){
    $query->where('suserid' , $userid);
    $query->orwhere('riemailid' , $user); 
}

您需要在查询中使用"use"关键字。

还要写或在哪里查询,如下所示:-

EmailBox::join('users as us', 'EmailBox.suserid', '=', 'us.id')
          ->where('status' , 'Delete')
          ->where(function($query) use ($userid, $user){
              $query->where('suserid' , $userid)
                    ->orwhere('riemailid' , $user); 
          })->paginate(5);

希望它能帮助你:)

确保变量不写在''(单引号)中

 if(Auth::check()){
        //if(Auth::user()->email!="")
        $user=Auth::user()->email;
        $userid=Auth::user()->id;
        $lists = EmailBox::join('users as us', 'EmailBox.suserid', '=', 'us.id')
                            ->where('status' , 'Delete')
                            ->where(function($query){
                                $query->where('suserid' , $userid);
                                $query->orwhere('riemailid' , $user); 
                            })->paginate(5);
        $links = $lists->render();
        return view('front.index', compact('lists', 'links'));
    }