Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Model is saved with empty attribute value (NULL) to database

I try to save my model to the database. The model is saved into the database, but the values for the attributes are not set and stay empty.

enter image description here

It is a small model with only a few properties:

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Unit extends Model
{
    public $fillable = ['name', 'description', 'created_at', 'updated_at'];

    protected $table = 'units';

    // Allowed fields from forms
    // protected $guarded = ['ic'];

    /**
     * @var string
     */
    public $name = NULL;

    /**
     * @var string
     */
    public $description = NULL;
}

Controllers store function:

/**
 *
 * @param Request $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $this->validate(request(), [
        'name' => 'required|max:80|regex:/^[\pL\s\-]+$/u',    //regex: only allows letters, hyphens and spaces explicitly',
        'description' => 'required',
        'image' => 'required|image',
    ]);

    $unit = new Unit();

    $unit->description = $request->description;
    $unit->name = $request->name;

    echo $unit->description . PHP_EOL;  //Outputs "example description"
    echo $unit->name . PHP_EOL;   //Outputs: "example name"

    $unit->save();
    ...

I am confused, it should work. What am I doing wrong?

UPDATE:

The object $unit after save():

Unit {#190 ▼
  +fillable: array:2 [▼
    0 => "name"
    1 => "description"
  ]
  #table: "units"
  +name: "example name"
  +description: "example description"
  #connection: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: true
  #attributes: array:3 [▼
    "updated_at" => "2017-03-01 10:18:59"
    "created_at" => "2017-03-01 10:18:59"
    "id" => 27
  ]
  #original: array:3 [▼
    "updated_at" => "2017-03-01 10:18:59"
    "created_at" => "2017-03-01 10:18:59"
    "id" => 27
  ]
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #guarded: array:1 [▼
    0 => "*"
  ]
}
like image 768
Black Avatar asked Feb 28 '26 11:02

Black


1 Answers

Remove this:

   /**
 * @var string
 */
public $name = NULL;

/**
 * @var string
 */
public $description = NULL;
like image 111
Fatimah Avatar answered Mar 03 '26 00:03

Fatimah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!