I have an object in Illuminate that has a relation that can return different objets depending on a property of the main object
public function relation(){
switch($this->type){
case "type_1":
return $this->belongsTo('\Models\Type1', 'idElement');
break;
case "type_2":
return $this->belongsTo('\Models\Type2', 'idElement');
break;
default:
return null;
}
}
This produces an error of "Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation" when the "default" section is executed.
Also I can't instantiate a new Illuminate\Database\Eloquent\Relations\Relation()
as it is an abstract class.
I could create an empty table and return a relation to this empty table that will always return an empty value, but this is not a solution.
How can I return an empty relation in the default option?
UPDATE:
I have changed it to use polymorphic relations, but now the problem is: how to set a polymorphic relation as an optional relation?
Relation::morphMap([
'type_1' => \App\Models\Type1::class,
'type_2' => \App\Models\Type2::class
]);
....
public function relation(){
return $this->morphTo(null, 'type', 'idElement');
}