31

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"

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
faraz
  • 317
  • 1
  • 3
  • 11
  • You are fetching first record which match the email it will never return any error. – Kamal Paliwal Oct 27 '18 at 10:16
  • You can try the is_countable function of php. https://stackoverflow.com/a/54806221/3016038 – Vipul Feb 21 '19 at 11:44
  • 1
    here is quick fix https://sdtuts.com/warning-count-parameter-must-be-an-array-or-an-object-that-implements-fixed/ even parameter is not an `array` – user3151197 Mar 17 '19 at 09:36

11 Answers11

45

First of all you must understand that every error message PHP generates is meant to help you, and to make your code cleaner and less error-ridden.

When your code contains a bug, your best bet is to fix it, not to brush it off. Most answers here helps you with the latter. But you should really consider doing the former.

Every error message helps you to find a bug in the code. It means that errors shouldn't be intentional or "habitual". This way you won't have to silence them, and every error will mean that your code indeed encountered a bug.

Like in your case. You are using count() not on purpose. Not to actually count any values but only to tell whether returned value is empty or not. For this, you can use the variable itself:

if ($admin)

which is perfectly valid in PHP. Or, if you want to be more Catholic than the Pope, you can make it more strict but still on purpose

if ((bool)$admin === true)

So you should do every time when a function may return either false or array. This way, when accessing the returned value inside if, you will never get an error related to improper use of arrays. Unless the returned value will be non-empty and not an array - a situation for which this error message was invented exactly for!

So just make sure that every function that should return an array, returns an array, or any variable that should contain an array, contains an array. And you won't see this error again. Unless, due to some error, your code will return a non-array value unexpectedly. And this error message will help you to pinpoint this problem.

When things are not under your control, like, you need to get an array from an outside variable, do a validation first. For example, in case you are expecting an array from a form, that is obligatory, validate it and return an error, like

if (!$isset($_POST['options']) || !is_array($_POST['options'])) {
   // inform the user ad stop execution
} else {
    $options = $_POST['options'];
}
// now you can safely use count() on $options

In case the array is optional, you may initialize it as empty array:

if (!$isset($_POST['options'])) {
    $options = [];
} elseif (!is_array($_POST['options'])
   // inform the user ad stop execution
} else {
    $options = $_POST['options'];
}
// now you can safely use count() on $options

And only as a last resort you may silence this error, using a condition like this

count((is_countable($admin) ? $admin :[]))

or casting offered below

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Dmytro Huz
  • 1,514
  • 2
  • 14
  • 22
43

You may cast a variable to array. But be careful: using array($variable) will give you incorrect result, returning an array with a single value of $variable in it, always returning 1 as a count.

(array) type casting operator must be used instead:

count((array)$variable));
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Jericho Manalo
  • 646
  • 6
  • 4
10

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

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
}
Teoman Tıngır
  • 2,766
  • 2
  • 21
  • 41
  • i try first method and use if($admin) but error comes it go on next and show blank page not showing if block message statment – faraz Oct 27 '18 at 10:35
  • and if i use get() method and if($admin) then this error comes "Property [status] does not exist on this collection instance." – faraz Oct 27 '18 at 10:38
  • @faraz error totally make sense because get method gives you a collection. And before the getting status, you need to select item first. like `$admin->{0}->status`, And I don't know what are you doing with credentials information so I can't know that why you're getting blank page. You can anytime check your code using dd method. For example put a dd method inside of if statment and check is if statement works well ? Or share with us more of your code to help you – Teoman Tıngır Oct 27 '18 at 11:03
5

You can cast the variable to an array:

count((array)$variable);

If it's null then it will become an empty array.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Arijit Das
  • 84
  • 1
  • 5
3

You should check if it is null instead of count, because you ask for one result with first() just this

if($admin)

will do it.

if you use return a collection using ->get() then you can check $admin->count().

nakov
  • 13,938
  • 12
  • 60
  • 110
2

$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) {
    //
}
Ali Farhoudi
  • 5,350
  • 7
  • 26
  • 44
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.
}
sonu pokade
  • 377
  • 3
  • 11
  • Have you mention Admin model in controller. and one more thing you need to do is. $request->input('email'); first make this change and before going further just echo "
    ";
    print_r($admin);
    – sonu pokade Oct 27 '18 at 12:52
  • No sir its not working 1st if condition is working when it comes in then again if($admin->status==0) is not working his else part is working I dnt know why its comes error on if part why it is not working – faraz Oct 27 '18 at 15:51
  • @faraz Means now you dont get the error regrading count? – sonu pokade Oct 27 '18 at 16:42
  • Yes because i replace count with !empty and error comes in inner if condition if($admin->status==0) is not working and else condition is working when i give correct code – faraz Oct 27 '18 at 16:44
  • Its not compare with zero because inactive email status is 0 but when i use active email which is else part sith status is 1 it works – faraz Oct 27 '18 at 16:46
  • protected function credentials(Request $request) { $admin=admin::where('email',$request->email)->first(); if(!empty($admin)) { if($admin->status){ return ['email'=>$request->email,'password'=>$request->password,'status'=>1]; } else{ return ['email'=>'inactive','password'=>'You are not an active person, Please contact to admin']; } } return $request->only($this->username(), 'password'); } – sonu pokade Oct 27 '18 at 17:18
  • trying to get the value of $admin->status by manually adding email in query so you need 2 admin one is which has status 0 and second is wiith status 1.and figure it out on what you get and only after that making condition as $admin->status... – sonu pokade Oct 27 '18 at 17:46
0
$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))
rajesh
  • 49
  • 5
0

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');
    }
paranoid
  • 6,799
  • 19
  • 49
  • 86
0

In my case count was 1 even when I got [] from api

so I had to put it in try catch

try{
 $propertyId = arr[0].propertyId;
}catch(\Exception $e) {
return response()->json(['success' => 'false']);
}
Sudhanshu Garg
  • 105
  • 1
  • 10
-2

add this your controler this code:

 $user = User::where('email',$request->email)->first();
        if ($user){
            return redirect()->back()->with('errors','We cant find a user with that e-mail address.');
        }else{
            $user->password = bcrypt($request->new_password);
            $user->update();
            return redirect()->back()->with('success','Success');
        }
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30