Reputation: 21443
This is a simple problem. When I call save()
on my model, the columns are not getting added to the database. Here is my model:
class User extends Eloquent implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
public $email; ## string (used as username)
public $name; ## string
public $address; ## string
public $phone; ## string nullable
}
and here's the code to add the row
$data=Input::all();
if ($data['password'] != $data['confirm-password']){
return Redirect::to('/register');
}
$user = new User;
$user->email=$data['email'];
$user->password=Hash::make($data['password']);
$user->name=$data['first']." ".$data['last'];
$user->address=$data['street'].", ".$data['city'].", ".$data['state']." ".$data['zip'];
$user->phone=$data['phone'];
$user->save();
echo "<pre>";
var_dump($user);
echo "</pre>";
The var_dump
is outputting the proper values in the model. Every field in the Model matches exactly the name of the column in the database. The password hash is getting added and a new row is being created, but every other column is showing up empty. What am I doing wrong?
Upvotes: 0
Views: 250
Reputation: 7578
You can't to declare columns as object properties. Laravel will do the magic for you. Remove these lines:
public $email; ## string (used as username)
public $name; ## string
public $address; ## string
public $phone; ## string nullable
Explanation:
Laravel's Eloquent make use of PHP's __set()
(reference) which is triggered when you are setting to an undefined property. Laravel then performs a few internal tasks via Model::setAttribute()
to populate the model in its own way.
See Illuminate/Database/Eloquent/Model.php:
public function __set($key, $value)
{
$this->setAttribute($key, $value);
}
public function setAttribute($key, $value)
{
// First we will check for the presence of a mutator for the set operation
// which simply lets the developers tweak the attribute as it is set on
// the model, such as "json_encoding" an listing of data for storage.
if ($this->hasSetMutator($key))
{
$method = 'set'.studly_case($key).'Attribute';
return $this->{$method}($value);
}
// If an attribute is listed as a "date", we'll convert it from a DateTime
// instance into a form proper for storage on the database tables using
// the connection grammar's date format. We will auto set the values.
elseif (in_array($key, $this->getDates()))
{
if ($value)
{
$value = $this->fromDateTime($value);
}
}
$this->attributes[$key] = $value;
}
Upvotes: 2