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

Ligonsker's avatar

Get value if not null in the same line of query

Using Laravel 6 and PHP 7.4,

is it possible to check the following for non-existing data before accessing the value but together with the query? In order to avoid some cases of "Trying to get property of non-object" (Two examples, one with query builder and one with eloquent)

DB::table('table')->where(...)->value('column');

// or

Auth::user()->someRelationship->column;

but if the value of the column is null, return maybe empty string? Or I will have to do it in steps:

$query = DB::table('table')->where(...);
return $query->column ?? "";

// or

$query = Auth::user()->someRelationship;
return $query->column ?? "";

I remember I saw somewhere the null coalescing operator being used somehow in the query, just couldn't get it to work again

0 likes
7 replies
click's avatar

You can't use it in the query, you can use it on the result of the query

$value = Auth::user()->someRelationship->column ?? '';
$value = \DB::table()->where()->first()->column ?? '';

If someRelationship is null above will result in an empty string.

1 like
Ligonsker's avatar

@click thank you! I just remember I once saw (here I think), the usage of ??-> or something weird like that

kokoshneta's avatar

@Ligonsker It won’t work at all since the nullsafe operator is new in PHP 8 and you say you’re on PHP 7.4.

1 like

Please or to participate in this conversation.