1
votes

I have a model that doesn't seem to be mass assignable, even though I have filled in the $fillable fields:

class LoginAttempt extends Eloquent
{
    protected $table = 'login_history';
    protected $fillable = array('remote_addr', 'user_agent', 'successful');

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Which is using this schema:

  • login_history
    • id
    • user_id
    • remote_addr
    • user_agent
    • successful
    • created_at
    • updated_at

When I mass assign the instance with these variables,

$vars = array(
    'remote_addr' => $_SERVER['REMOTE_ADDR'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'],
    'successful' => false,
);

print_r($vars);
=> array('remote_addr' => '127.0.0.1', 'user_agent' => 'Moz..', 'successful' => false);

new LoginAttempt($vars);
=> LoginAttempt instance, attributes => array()

LoginAttempt::create($vars);
=> LoginAttempt instance, attributes => array()

$login = new LoginAttempt;
$login->fill($vars);
=> LoginAttempt instance, attributes => array()

$login = new LoginAttempt;
$login->remote_addr = $vars['remote_addr'];
$login->user_agent= $vars['user_agent'];
$login->successful= $vars['successful'];
=> LoginAttempt instance, attributes => array('remote_addr' => '..', 'user_agent' => '..', 'successful' => false)

I think I'm using $fillable as the docs describe - why isn't mass assignment working in this case?

1
Thanks for this great example of working code. :)Yevgeniy Afanasyev

1 Answers

4
votes

Turns out this was a bug in Laravel (has been fixed) - all fields are guarded by default (protected $guarded = array('*');) which then took precedence over $fillable.