Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 1 year ago.
0

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');
		});
	}
0

I have the same migration. You can see it in this gist: https://gist.github.com/Stichoza/444b16aecc26b73b9ede

Last updated 8 years ago.
0

Do you get the same error when trying this in php artisan tinker:

\App\Category::create(['parent_id' => null, 'title' => 'foobar']);
0

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!

Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Stichoza stichoza Joined 7 Dec 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.