我正在学习如何使用Laravel框架,但我在填充模型时遇到了麻烦.以下是我的代码:

The model Event:

<?php
class Event extends Eloquent {
  //Some functions not used yet
}

下面是控制器中的代码:

$event = new Event();
$event->fill(array('foo', 'bar'));
print_r($event->attributes);

So, why the print_r is displaying an empty array?

推荐答案

The attributes is a protected property. Use $obj->getAttributes() method.

Actually. at first you should change the model name from Event to something else, Laravel has a Facade class as Illuminate\Support\Facades\Event so it could be a problem.

Regarding the fill method, you should pass an associative array to fill method like:

$obj = new MyModel;
$obj->fill(array('fieldname1' => 'value', 'fieldname2' => 'value'));

Also make sure you have a protected $fillable (check mass assignment) property declared in your Model with property names that are allowed to be filled. You may also do the same thing when initializing the Model:

$properties = array('fieldname1' => 'value', 'fieldname2' => 'value');
$obj = new ModelName($properties);

最后,打电话:

// Instead of attributes
dd($obj->getAttributes());

Because attributes is a protected property.

Laravel相关问答推荐

为什么在Blade 文件中输出用户通知时出现错误?

通过 laravel 中的 url 传递多个字符串作为参数以从数据库中删除特定数据

函数接受 Laravel 集合对象,尽管只允许使用字符串

Laravel belongsTo 关系 - 试图获取非对象的属性

插入重复键时,laravel eloquent 忽略错误

如何使用 laravel eloquent 获得select count(*) group by

Laravel 表 * 没有名为 * 的列

laravel 5 中的登录事件处理

在 Laravel 5.4 中将中间件应用于除 `setup/*` 之外的所有路由

laravel:Eloquent的例子将数据插入数据库

如何在 Laravel 4 中使用 SHA1 加密而不是 BCrypt?

Laravel Mix 生成字体到另一个目录

Laravel 验证 pdf mime

Laravel:方法[显示]不存在

Select,where JSON 包含数组

在 vue.js 中使用 Laravel 的Gate/Authorization

Laravel 获取文件内容

你如何在 Laravel 中的每个响应上强制一个 JSON 响应?

使用 Queue::fake() 测试监听器

如何在没有日志(log)、没有信息的情况下调试 Laravel 错误 500