首页 文章

count()参数必须是在laravel中实现可数的数组或对象

提问于
浏览
1

这是代码:

protected function credentials(Request $request)
{
    $admin=admin::where('email',$request->email)->first();
    if(count($admin))
    {
       if($admin->status==0){
           return ['email'=>'inactive','password'=>'You are not an active person, Please contact to admin'];
           }
           else{
               return ['email'=>$request->email,'password'=>$request->password,'status'=>1];
           }
       }
       return $request->only($this->username(), 'password');
    }

当我运行代码时,此错误变为:

“count():参数必须是实现Countable的数组或对象”

5 回答

  • 1

    你应该检查它是否为null而不是count,因为你只需要 first() 就可以得到一个结果

    if($admin)
    

    会做的 .

    如果你使用 ->get() 返回一个集合,那么你可以检查 $admin->count() .

  • 1

    请注意,在这里,当您使用 count() 方法时,应该有可数元素,如数组或对象 .

    Admin::where('email',$request->email)->first();
    

    first() 方法为您提供单个元素,而不是集合或数组 . get() 方法返回可查找具有找到元素的集合

    您可以直接检查变量本身是否已定义或为null,而不是使用count

    if($admin){
      // do something here
    }
    

    或者您可以使用 is_null() 方法

    if(!is_null($admin)){
      // do something here
    }
    
  • 0

    $admin 变量既不是数组也不是实现可数的对象 . 当您使用 first() 时,如果找到记录,结果将是模型对象,否则它将为null . 对于这种情况,您可以使用:

    if (!empty($admin)) {
        //
    }
    

    只需将 if (count($admin)) 替换为 if (!empty($admin)) 即可 .

    当您使用 get() 方法获取多个记录时,您可以通过以下方式检查:

    if ($admins->count() > 0) {
        //
    }
    
  • 0
    $admin = null;
    var_dump(count($admin));
    

    output :警告:count():参数必须是在第12行上实现Countable的数组或对象//从PHP 7.2开始

    如果条件应该像:

    if(isset($admin) && count($admin))
    
  • 1
    Well,
    $admin=Admin::where('email',$request->email)->first();
    //It will always return an **object**.
    And make sure you included Admin model in your controller like as.
    Use App\Admin;
    at the same time check that you will have to mention which field of table needs to be fillable like in your model such as 
    protected $fillable = [
    'first_name',
    'last_name'
    ];
    
    whatever data you will going to save in your database.
    and then check object is null or not
    I mean is.
    
    if($admin && $admin!==null){
      //do whatver you want to do.
    }
    

相关问题