1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Accessing model attributes inside relationship in laravel returns null when eager loading

Discussão em 'Outras Linguagens' iniciado por Mohamed DS, Outubro 7, 2024 às 14:12.

  1. Mohamed DS

    Mohamed DS Guest

    When accessing model attrs inside relation logic in laravel the attrs are all null when eager loading, if lazy loading it works fine.

    Model relation :

    public function organization()
    {
    return $this->belongsTo(Organization::class, 'organization_id');
    }

    public function currentOrder()
    {

    // Note that this will not work if eager loading the relation
    // for some reason all model's attrs are null when eager loading
    $subscription = $this->organization->currentAdhesionSubscription;

    if ($subscription) {
    return $this->morphOne(Order::class, 'parent')
    ->whereHas('ticketsWithPrice', fn($q) => $q->where('ticket_id', $subscription->ticket_id));
    }
    }


    If lazy load the relation it works :

    $model->load('currentOrder');
    $model->currentOrder;


    If eager loading it won't work :

    $model = Model::with('currentOrder')->first();
    $model->currnetOrder // Error of accessing "currentAdhesionSubscription" on null which is organization which is a relation, but even when I access an attr of the model such as id it returns null when eager loading


    Why model attrs are null when being accessed from whithin an eager loaded relation ?

    Continue reading...

Compartilhe esta Página