Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lbecket's avatar
Level 39

Distinguish between null and undefined in Request

I want to be able to give users the ability to nullify an existing value, salesperson_id in this example, through an external API call. My thought was that they could send a property with a value of null, but I also need to be able to preserve values when the property is absent from the request. I've tried isset(), empty(), is_null(), $request->salesperson_id === null and everything evaluates the same way.

Can PHP/Laravel differentiate between a property that is set to null and one that hasn't been defined at all?

To illustrate further, here are three possible calls with the desired outcome in the comments:

{
	"order_id": 1234,
	"salesperson_id": 246913022	// integer value gets assigned... this works fine
}

...

{
	"order_id": 1234,
	"salesperson_id": null	// salesperson_id value should become null... also works fine
}

...

{
	"order_id": 1234,
	// salesperson_id property not set so any previously assigned value should remain unaffected, but this results in $request->salesperson_id === null and is nullifying a value that I want to preserve
}

Thanks!

0 likes
5 replies
Snapey's avatar
Snapey
Best Answer
Level 122

how about $request->has('salesperson_id')

2 likes
lbecket's avatar
Level 39

@Snapey I can't believe that I forgot about $request->has... that's why you're #1, Snapey. Thank you!

jlrdw's avatar

@lbecket just fyi it uses array_key_exists in the background. Uses Symfony parameter bag:

quote

   /**
     * Returns true if the parameter is defined.
     *
     * @return bool true if the parameter exists, false otherwise
     */
    public function has(string $key)
    {
        return \array_key_exists($key, $this->parameters);
    }

unquote

2 likes

Please or to participate in this conversation.