laraveleloquent-relationship

How to Create Conditional BelongsTo Relationships in Laravel Models?


I need to set up conditional belongsTo relationships. Specifically, I have ModelA that can belong to either ModelB or ModelC based on a column value (related_id). For example, if related_id is 1, it should relate to ModelB; if it's 2, it should relate to ModelC. The relationships are stored in the same field. Here's a simplified version of what I'm trying to achieve:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class ModelA extends Model
{
    public function modelB(): BelongsTo
    {
        return $this->belongsTo(ModelB::class, 'related_id', 'id');
    }

    public function modelC(): BelongsTo
    {
        return $this->belongsTo(ModelC::class, 'related_id', 'id');
    }
}

I want to be able to load the correct relationship dynamically based on the value of related_id without having to use conditional logic in my repositories or elsewhere. Is there a way to handle this directly within the model?

I tried using where directly in the belongsTo method, but it didn't work as expected


Solution

  • I think it is better in this case to use Polymorphic one to many relationship.

    Your ModelA Table should contains those columns:

    modelable_id - integer
    modelable_type - string
    

    Your model will be like that:

    namespace App\Models;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\BelongsTo;
    
    class ModelA extends Model
    {
         public function ModelAable(): MorphTo
        {
            return $this->morphTo();
        }
     }
    

    You can see laravel docs for more details on how to apply it: https://laravel.com/docs/11.x/eloquent-relationships#one-to-many-polymorphic-relations