empty() , isset() 无法检查变量是否在 laravel 中有数据

empty() , isset() not working to check if a variable has data in laravel

$mobile_no = LoginModel::where(['mobile_no' => $request->mobile_no])->get(['mobile_no']);
 dd($mobile_no);
 if(!empty( $mobile_no )){
     $request->session()->put('error','This mobile no. Already Exist!');
     return view::make('errors.503'); 
}

我使用 if(isset($mobile_no)) 也仍然重定向到 error page$mobile_no 是空的。

我使用 dd($mobile_no) 检查了变量并显示了这个输出 Collection {#188 ▼ #items: [] }

get() 方法总是returns 一个集合。因此,您需要使用 first() 或仅使用 count() 以便于比较。

$result = LoginModel::where('mobile_no', $request->mobile_no)->count();

if($result) {
    $request->session()->put('error','This mobile no. Already Exist!');
    return view::make('errors.503');
}

您还可以使用验证器检查唯一手机号码并抛出错误。你可以在这里阅读 https://laravel.com/docs/5.4/validation#rule-unique