I am trying to use the array_diff
PHP function, the problem is that I am trying to do it with two variables that I have in my function.
$var1 = Model::all();
$var2 = Model1::all();
// Trato de eliminar valores repetidos
$var3 = array_diff($var1, $var2);
The error it throws me is:
array_diff(): Argument #1 is not an array
The problem has already been mentioned,
$var1
and they are$var2
not arrays , it is what you expectarray_diff()
. Yes, it is using methods of the class to work with collections, which is what it returns .Laravel
Illuminate\Support\Collection
All()
For your example it would be to use $collection->diff($collection2)
The problem
The error message is very clear:
It's telling you that argument 1, that is,
$var1
is not an array.As is evident, it
array_diff
must receive two arrays as a parameter, as the PHP Manual shows :It is evident that the call to
Model::all();
is not actually returning an array .To test it, just run this line of code:
The screen output will tell you what it is
$var
, if it were an array you should see something like this:If it doesn't say
array
at the beginning it's not an array...The solution
You should review the method
all
of the classModel
, verifying that said method returns an array.What it is returning to you is an Illuminate\Database\Eloquent\Collection. This object in turn has several methods to operate with a collection of elements.
In your case, I inform you that one of those methods is toArray(), which returns an array.
you can try with
$var1 = Model::all()->toArray();
To see what an array returns, what you'll have to find out is if it's worth it for your array_diff, because it will most likely return an array of objects from your entity... Array_diff may not return what you expect...
I managed to fix by converting the object to arrays