Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value if relationship doesn't exist

Using Laravel Datatables package: https://github.com/yajra/laravel-datatables

I am eager loading belongsTo relationships. However, for some rows, the relationship might not exist, and the relationship_id column would be null.

This is causing an issue with datatables:

{ data: 'relationship.name' },

It throws an error if the relationship doesn't exist. How would I set a default value for this particular column if the relationship was not found? I've tried using editColumn, which worked for sorting, but not for searching.

like image 302
kjdion84 Avatar asked Dec 17 '22 22:12

kjdion84


1 Answers

You can use withDefault():

public function relationship()
{
    return $this->belongsTo(...)->withDefault(['name' => 'default']);
}
like image 135
Jonas Staudenmeir Avatar answered Dec 20 '22 17:12

Jonas Staudenmeir