Laravel model attributes null when i saved it but but I have validated them in the constructor

  laravel, php

working with Laravel PHP, I have this model with a constructor where i set the attributes:

class NutritionalPlanRow extends Model
{
    use HasFactory;

    private $nutritional_plan_id;
    private $aliment_id;
    private $nomeAlimento;

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

        parent::__construct($attributes);

        if($plan){
            $this->nutritional_plan()->associate($plan);
            $this->nutritional_plan_id = $plan->id;
        }
        if($aliment){
            $this->aliment()->associate($aliment);
            $this->aliment_id = $aliment->id;
            $this->nomeAlimento = $aliment->nome;
        }

    }

    /**
     * Get the plan that owns the row.
     */
    public function nutritional_plan()
    {
        return $this->belongsTo('AppModelsNutritionalPlan');
    }

    /**
     * Get the aliment record associated with the NutritionalPlanRow.
     */
    public function aliment()
    {
        return $this->belongsTo('AppModelsAliment');
    }

    /**
     * The attributes that aren't mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * Get the value of nomeAlimento
     */
    public function getNomeAlimentoAttribute()
    {
        return $this->nomeAlimento;
    }

    /**
     * Get the value of plan_id
     */
    public function getNutritional_Plan_IdAttribute()
    {
        return $this->nutritional_plan_id;
    }

    /**
     * Get the value of aliment_id
     */
    public function getAliment_IdAttribute()
    {
        return $this->aliment_id;
    }
}

Then I have a controller where I initialize the object:

public function addAlimentToPlan(Request $request){

        $planId = $request->planId;
        $alimentId = $request->alimentId;

        $validatedData = Validator::make($request->all(), [
        'planId' => ['required'],
        'alimentId' => ['required'],
    ]);

    if ($validatedData->fails()) {
        return back()->withErrors($validatedData, 'aliment');
    }

    $plan = NutritionalPlan::find($planId);
    $aliment = Aliment::find($alimentId);

    $nutritionalPlanRow = new NutritionalPlanRow($plan, $aliment);

    Log::info('Nome Alimento '.$nutritionalPlanRow->getNomeAlimentoAttribute());

    $nutritionalPlanRow->save(); //

    Toastr::success( 'Alimento aggiunto', '',
        ["positionClass" => "toast-bottom-right",
        "closeButton" => "true"]);

    return back();
}

The save operation return this error:
SQLSTATE[23502]: Not null violation: 7 ERRORE: null value in column "nomeAlimento" of relation "nutritional_plan_rows"

but logging the $nutritionalPlanRow->getNomeAlimentoAttribute() the attribure is enhanced.

Someone can help me?
Thank you.

Source: Laravel

Leave a Reply