Laravel object value with Blade statement does not work if model has accessor

  accessor, laravel, laravel-blade, php

i have an Laravel object model with accessor:

class NutritionalPlanRow extends Model
    use HasFactory;

    private $nomeAlimento;

    public function __construct($aliment = null,
                                array $attributes = array())  {


            $this->nomeAlimento = $aliment->nome;

    public function aliment()
        return $this->belongsTo('AppModelsAliment');

    protected $guarded = [];

    public function getNomeAlimentoAttribute()
        return $this->nomeAlimento;

and i want to print the nomeAlimento value in a Blade page with Blade statement, for example:

     @foreach( $plan->nutritionalPlanRows as $planRow )
             {{ $planRow->nomeAlimento}}

but the value inside the table cell is not printed, as if $planRow->foodName is null. In reality it is not empty, in fact if I print {{$planRow}} the structure of the object is complete, and all the attributes are set.
I noticed that if in the model I remove the accessor (getNomeAlimentoAttribute()), then the value in the blade page is correctly printed.



Source: Laravel

Leave a Reply