count() parameter must be an array or an object th

2020-04-07 15:40发布

This is code here:

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

When i run the code this error become:

"count(): Parameter must be an array or an object that implements Countable"

标签: php laravel
9条回答
够拽才男人
2楼-- · 2020-04-07 16:22

This is my solution:

count(array($variable));

hope it works!

查看更多
Animai°情兽
3楼-- · 2020-04-07 16:23

$admin variable is neither array nor object that implements countable. When you use first() the result will be a model object if record is found else it will be null. For this condition you can use:

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

Just replace if (count($admin)) with if (!empty($admin)).

And when you use get() method to get multiple records you can check by:

if ($admins->count() > 0) {
    //
}
查看更多
We Are One
4楼-- · 2020-04-07 16:25

It happens because of in PHP 7.2 NULL in count() return Warning. You can try to change

count($admin)

to

count((is_countable($admin)?$admin:[]))
查看更多
在下西门庆
5楼-- · 2020-04-07 16:32

Note that here, When you use the count() method, there should be countable element, like an array or object.

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

But the first() method give you single element, not a collection or array. The get() method returns you countable a collection with found elements

Instead of using count you can directly check variable itself is it defined or null

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

or you can use is_null() method

if(!is_null($admin)){
  // do something here
}
查看更多
家丑人穷心不美
6楼-- · 2020-04-07 16:32

Use isset($admin->id) instead of count($admin)

Try this :

protected function credentials(Request $request)
{
    $admin=admin::where('email',$request->email)->first();
    if(isset($admin->id)))
    {
       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');
    }
查看更多
Bombasti
7楼-- · 2020-04-07 16:34
$admin = null;
var_dump(count($admin));

output: Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // as of PHP 7.2

if condition should be like:

if(isset($admin) && count($admin))
查看更多
登录 后发表回答