Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill method in Laravel not working?

Tags:

php

laravel

I am learning how to use Laravel framework but I am having troubles with filling a Model. Here is my code:

The model Event:

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

And here is the code in the controller:

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

So, why the print_r is displaying an empty array?

like image 902
marc_aragones Avatar asked Jun 19 '14 09:06

marc_aragones


Video Answer


1 Answers

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);

Finally, call:

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

Because attributes is a protected property.

like image 65
The Alpha Avatar answered Oct 11 '22 12:10

The Alpha