Laravel - 模型以空属性保存到数据库

时间:2017-03-01 10:09:52

标签: php laravel laravel-5.4

我尝试将模型保存到数据库中。模型将保存到数据库中,但属性的值未设置并保持为空。

enter image description here

这是一个只有少数属性的小型模型:

<?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;
}

控制器存储功能:

/**
 *
 * @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();
    ...

我很困惑,它应该工作。我做错了什么?

更新

$unit之后的对象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 => "*"
  ]
}

3 个答案:

答案 0 :(得分:4)

删除它:

{"root":""}

答案 1 :(得分:1)

如前所述,您必须从模型类中删除这两个属性。这是因为当定义这些属性时,不会有神奇的$obj->attributes[]运行,因此function TESTgetFileName() { Logger.log(getFileName('0B4ptELk-D3USVi1NZ3ZGbkhqYXc')); // ^^^^^^^^^^ file ID ^^^^^^^^^ } function getFileName(id) { var file = DriveApp.getFileById(id); var fileName = file.getName(); var strFolders = getFolders(file); return strFolders + '/' + fileName; } function getFolders(object) { var folders = object.getParents(); if (!folders.hasNext()) { return 'My Drive'; } var folder = folders.next(); var folderNames = []; while (folder.getParents().hasNext()) { var folderName = folder.getName(); folderNames.unshift(folderName); folder = folder.getParents().next(); } return folderNames.join('/'); } 不会被填充值。

答案 2 :(得分:0)

尝试取消注释$guarded属性并保护id

protected $primaryKey = 'id';

我认为它与以下属性有关:

#guarded: array:1 [▼
    0 => "*"
]

这可能意味着一切都得到了保护。

<强>更新

受保护的属性应该如何。

protected $guarded = ['id'];