A
A
akdes2017-08-23 16:33:08
Laravel
akdes, 2017-08-23 16:33:08

How to get a model property through another model's connection and not get an exception, in the absence of this?

Hi all.
I know that the question is posed very strangely, because it is difficult to describe the problem / scenario in one line: I
want:

$value = $modelA->modelB()->where("foo", "bar")->first()->value;

account for
$modelB = $modelA->modelB()->where("foo", "bar")->first();
if($modelB) {
   $value = $modelB->value;
}

1. It would be desirable as in the first example, but at the same time not to get the 500th if there is no property, but only NULL.
2. How appropriate is this approach? The desire arose only because of the reduction and readability of the code (IMHO) ...
Thank you very much

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Melikhov, 2017-08-23
@amelihovv

One way is described at
laraveldaily.com/belongsto-default-models-no-need-...
The second is to use ?? operator

$value = $modelA->modelB()->where("foo", "bar")->first()->value ?? null;

A
Artyom Belousov, 2017-08-23
@flygrounder

Use try/catch. If you often write like this, then write a function that handles it through try / catch

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question