0

I have these two arrays as a result of requests:

$f = DocsPf::where('renda', '=', 2)->where('tipo', '=', 'R')->pluck('id');
$f = [4,5,6,7,8,9,10]

And

$d = Documento::where('user_id', '=', $id)->pluck('cad_doc_id');
[4,5,6,7,8]

Now I want to make a request to a model only with the difference between those arrays, like:

$missing = Docs::where('id', '=', 9)->first();

and

$missing = Docs::where('id', '=', 10)->first();

I´ve did

$ids = array_diff($f, $d);
        return $ids;

...as the brother bellow wrote, but got hits error:

array_diff(): Expected parameter 1 to be an array, object given

Any helps, please?

1

1 Answer 1

2

You can use array_diff() on the two arrays to get unique values:

$array1 = [4,5,6,7,8,9,10];
$array2 = [4,5,6,7,8];

$uniqueIds = array_diff($array1, $array2); // `[9, 10]`

$missing = Docs::whereIn("id", $uniqueIds)->get();
// Will return a `Collection` of `Doc` models based on the passed `ids`

-- Edit --

If $array1 and $array2 are Collections, you can use the diff() function:

$array1 = collect([4,5,6,7,8,9,10]);
$array2 = collect([4,5,6,7,8]);

$uniqueIds = $array1->diff($array2);
$missing = Docs::whereIn("id", $uniqueIds)->get();
// Note: You may need to do `$uniqueIds->toArray()` if it complains further.

One more alternative, you can convert $array1 and $array2 to arrays before using array_diff()

$uniqueIds = array_diff($array1->toArray(), $array2->toArray());

It's a little redundant, but should help demonstrate the difference between an array and a Collection

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, @Vince, but I´ve forgot to say that the array is a result of a request... so, maybe it is not an array, but an object.
It's a Collection, which is a fancy helper class for arrays in Laravel. They can easily be converted to an array, via ->toArray(), or you can use ->diff() as demonstrated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.