Search code examples
phplaravel-5issetis-empty

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'); 
}

I used if(isset($mobile_no)) also still redirecting to error page while $mobile_no is empty.

I checked variable using dd($mobile_no) and showing this output Collection {#188 ▼ #items: [] }


Solution

  • The get() method always returns a collection. Therefore you need to use first() or just use count() for easy comparison.

    $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');
    }
    

    You could also use the validator to check for unique mobile number and throw errors. You can read about it here https://laravel.com/docs/5.4/validation#rule-unique