3

I have an intersect in my update method:

$inputs = $request->intersect('message','name','email','is_read');

If i send an update request where is_read=0 the intersect returns an empty array. Works fine with anything else (false, 1 etc)

Any tips?

Thanks!

user3844579
  • 485
  • 1
  • 8
  • 29

1 Answers1

7

ALERT Try to move to another implementation and stop using intersect() method, it will be removed from the future versions of Laravel: Link

IF you mean that the is_read key is missing from the final array (and not the the whole array is empty, see my comment), this is because of the implementation of the intersect() method.

The intersect method simply wraps the only() method of the Illuminate\Http\Request class and do an array_filter over the result.

This is the implementation:

/**
 * Intersect an array of items with the input data.
 *
 * @param  array|mixed  $keys
 * @return array
 */
public function intersect($keys)
{
    return array_filter($this->only(is_array($keys) ? $keys : func_get_args()));
}

In your case, we can decompose the code as this:

step1

$results = $request->only('message','name','email','is_read');

At this point, $results is

Array
(
    [message] => message
    [name] => name
    [email] => email
    [is_read] => 0
)

However, at step2

step2

$filteredResults = array_filter($results);

The result becomes

Array
(
    [message] => message
    [name] => name
    [email] => email
)

And this is because of how array_filter works. It expect an array as the first parameter, then an optional callback (used to filter the array) and a flag.

From php reference

What happens when no callback is provided (like in this case?)

If no callback is supplied, all entries of array equal to FALSE (see converting to boolean) will be removed.

If you look at the link converting to boolean you'll see that 0 (zero) is assumed to be FALSE and, for that reason, removed from the array.

LombaX
  • 17,265
  • 5
  • 52
  • 77
  • Thank you for the detailed description, i have updated my code, now instead of 0 i return a false as string and then convert that to a boolean false and it works that way – user3844579 Apr 23 '17 at 19:43