Reputation: 1201
MySql throws error an error when trying to create a new instance of a model. The user_id
field is valid, I've tried to set it manually but it didn't work either. User with id 1
exists.
Error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`production_paperclip`.`widgets`, CONSTRAINT `widgets_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION) (SQL: insert into `widgets` (`updated_at`, `created_at`) values (2014-07-21 02:14:12, 2014-07-21 02:14:12))
Query:
\Widget::create(array(
'title' => \Lang::get('widget.news_localizer.install.title'),
'strictName' => self::strictName,
'userSettings' => null,
'description' => \Lang::get('widget.news_localizer.install.description'),
'bodyTemplateName' => 'admin.dashboard.widgets.news_localizer.index',
'user_id' => \Auth::id(),
));
Model:
class Widget extends \Eloquent
{
use SoftDeletingTrait;
protected $fillable = array('*');
/**
* Get the user which installed the widget
* @return Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo('User');
}
}
Migration:
public function up()
{
Schema::create('widgets', function(Blueprint $table)
{
$table->increments('id');
// Name
$table->string('title', 256);
$table->index('title');
// Strict name
$table->string('strictName')->unqiue();
// User settings
$table->text('userSettings')->nullable();
// A short description
$table->string('description')->nullable();
// Body template name
$table->string('bodyTemplateName');
// User
$table->integer('user_id')->length(10)->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('no action');
$table->timestamps();
$table->softDeletes();
});
}
Upvotes: 0
Views: 349
Reputation: 92785
In the Widget
model change
protected $fillable = array('*');
to
protected $guarded = array('id', 'created_at', 'updated_at');
or
protected $fillable = array('title', 'strictName', 'userSettings', 'description', 'bodyTemplateName', 'user_id');
In other words you have to explicitly specify fillable fields (white list), or guarded fields (black list). *
works only for $guarded
, not $fillable
and error message clearly shows that. You have only timestamp fields being populated:
insert into `widgets` (`updated_at`, `created_at`)
values (2014-07-21 02:14:12, 2014-07-21 02:14:12)
Upvotes: 4