I have a belongTo relation, if join condition is matched then ok but when there is no data for this it returns null. In this case, I want it returns default value as I expected. This is what I try but it not success. Please help me?
class Task extends Model { use SoftDeletes; protected $table = 'tasks'; protected $fillable = [ 'name', 'description', 'project_id', ]; protected $with = ['project', 'status']; // this is expected public function getProjectAttribute($value) { return $value ?? ['id' => '', 'name' => '']; } /** * @return AppModulesComModelsProject */ public function project() { return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']); } }
With description attribute, I can override it but why I dont the same thing with project attribute? And how do I set where for project relation?
Like this Task::select(*)->project()->where(‘project.name’, ‘ABC’);.
Advertisement
Answer
I’ve never used Laravel — but… the documentation shows that you can set a default for belongsTo when using it for updating in order to avoid conditional checks. Perhaps it will work for selecting too.
You can try adding the default to the end of your call.
return $this->belongsTo(Project::class, 'project_id', 'id') ->select(['id', 'name']) ->withDefault([ 'project_id' => 'project.name', 'id' => 'ABC', ]);
Source: https://laravel.com/docs/6.x/eloquent-relationships#default-models
or
You could do a conditional check:
public function project() { $return $this->belongsTo(Project::class, 'project_id', 'id')->select(['id', 'name']); if( $return === null ) // return your default values else return $return; }