I've tried to create a model like yours and set up same constraints, and creating models with empty or null parent_id
works just fine.
Could you post your migration file?
Mine is like this:
public function up()
{
Schema::create('categories', function(Blueprint $table)
{
$table->increments('id');
$table->integer('parent_id')->unsigned()->nullable();
$table->string('name');
$table->foreign('parent_id')->references('id')->on('categories')
->onDelete('set null')
->onUpdate('cascade');
});
}
I have the same migration. You can see it in this gist: https://gist.github.com/Stichoza/444b16aecc26b73b9ede
Do you get the same error when trying this in php artisan tinker
:
\App\Category::create(['parent_id' => null, 'title' => 'foobar']);
Yes, it works.
I've found the problem. It seems that data is passed incorrectly from HTML form. I thought Eloquent would automatically convert an empty string to NULL if the field is nullable integer. I guess eloquent doesn't (and should not) know that much about schema.
BTW, if you run a query like this: insert into `categories` (`id`, `parent_id`) values (NULL, "NULL")
(last null is a string) it will obviously fail (as it should), but in the stack trace the last part of this query it would be written as values (NULL, NULL)
(both NULLs without quotes).
It's confusing I think. Will send a pull request for this.
Thanks for commenting anyways!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community