Laravel provides a rich of set of helper function, one of my favourite it's data_get
.
Often I use this function in my Api when I need to check if a model has a given relation.
Check the following code
public function toArray($request) { return [ 'id' => $this->id, 'title' => $this->title, 'description' => $this->description, 'category' => this->product->category->title
, 'product' => $this->product->title, 'is_active' => $this->is_active, ]; }
If the product does not have a category the Api crash.
To solve this issue I find it's very useful to use the Laravel data_get
helper.
According to Laravel documentation, the data_get()
helper allows you to get a value from an array or object with dot notation.
So you can secure your code in this way:
public function toArray($request)
{
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
//if relation exists return the value otherwise return null
'category' => data_get($this, 'product.category.title')
,
'product' => data_get($this, 'product.title'),
'is_active' => $this->is_active,
];
}