null check nested object laravel 1

null check nested object laravel

object_get($model, 'nested.relation.field')

Example:
$model = Book::with('author.country')->findOrFail($id);
$country_name = array_get($model->toArray(), 'author.country.name');
// or
$country_name = object_get($model, 'author.country.name');

Here is what the above code is Doing:
1. It’s using the with() method to eager load the author relationship.
2. It’s using the toArray() method to convert the model to an array.
3. It’s using the array_get() helper to get the value of the author.country.name key.

Similar Posts