Wednesday, March 1, 2017

Laravel - Model is saved with empty attributes to database

I try to save my model to the database, but the properties are not stored 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|http://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




via EdwardBlack

Advertisement