Use array_diff with Laravel

0

I'm trying to use the function array_diff of PHP, the problem is that I try 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 sends me is:

  

array_diff (): Argument # 1 is not an array

    
asked by Marcial Cahuaya Tarqui 05.11.2017 в 16:21
source

4 answers

1

The problem is already mentioned, $var1 and $var2 are not arrays , is what you expect array_diff() , yes you are using Laravel exist methods of the class Illuminate\Support\Collection to work with collections that is what returns All() .

For your example, use $ collection-> diff ($ collection2)

$var1 = Model::all();
$var2 = Model1::all();
$diff = $var1->diff($var2);
dd($diff->all());
    
answered by 05.11.2017 / 19:43
source
0

The problem

The error message is very clear:

  

array_diff (): Argument # 1 is not an array

It is telling you that argument 1, that is, $var1 is not an array.

As is evident, array_diff must receive two arrays in parameter, as shown by the PHP Manual :

array_diff ( array $array1 , array $array2 [, array $... ] )

Clearly the call to Model::all(); is not returning an array really .

To test it, just execute this line of code:

var_dump ($var);

The output on the screen will tell you what is $var , if it were an array you should see something like this:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

If you do not say array at the beginning of the whole it's not an array ...

The solution

You should check the all method of the class Model , verifying that this method returns an array.

    
answered by 05.11.2017 в 16:43
0

What is returning you is an Illuminate \ Database \ Eloquent \ Collection. This object 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 right for your array_diff, because it will most likely return an array of objects from your entity ... The array_diff may not return what you expect. ..

    
answered by 05.11.2017 в 17:11
0

I managed to solve by converting the object into arrays

$var1 = array();
foreach ($var1 as $key => $value) {
   $var1[] = $value->id;
}

$var2 = array();
foreach ($var2 as $key => $value) {
   $var2[] = $value->id;
}

$var3 = array_diff($var1, $var2);
    
answered by 05.11.2017 в 17:33