我尝试将我的模型保存到数据库。模型保存到数据库中,但属性的值未设置并保留为空。Laravel - 模型保存为空属性到数据库
这是一个小模型,只有几个属性:
<?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();
...
我很困惑,它应该工作。我究竟做错了什么?
UPDATE:
对象$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 => "*"
]
}
$ unit-> save()的返回值是什么,以及/storage/logs/laravel.log中记录的内容是什么? – veelen
为什么您将$ name和$ description定义为您班级的数据成员?问题在那里。 – Torgheh
@veelen,返回值为'true'。日志是空的,几分钟前我清空它,因为它包含了大约22000行。现在没有任何记录。 – Black