How to Resolve Laravel Error "local.ERROR Creating default object from empty value"
Thank you for your continued support.
This article contains advertisements that help fund our operations.
Table Of Contents
⇨ Click here for the Table of Contents of Laravel Articles
I wrote an article on how to resolve the error "local.ERROR Creating default object from empty value" in Laravel.
What kind of error occurs
local.ERROR: Creating default object from empty value {“exception”:“[object] (ErrorException(code: 0): Creating default object from empty value at /app/Http/Controllers/PostController.php:30)
This is the kind of error you will encounter.
Why does the error occur?
The fundamental cause of this error is that:
The database column is required but contains no data
This is the reason for the error.
In other words,
- In the database design, consider not making it mandatory in the first place
- In the database design, set a default value (initial value when no input is given)
- Check if the expected data is not being received
I think you should take appropriate action from these 3 points.
① How to make the database design not mandatory in the first place
By adding nullable() to the migration file, it is possible to allow null.
Modify the migration file
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable(); // Add nullable()
$table->timestamps();
});
This can be set for each column.
② How to set a default value in the database design
By adding default value in the migration file, you can insert the value set as default when no data is entered.
Modify the migration file
Schema::create('items', function (Blueprint $table) {
$table->id();
$table->string('title')->default('No Title'); // Add default()
$table->timestamps();
});
In this way, if no data is entered, "No Title" will be inserted into the column.
③ Check if the expected data is not being received
For example, in the controller:
$item = new Item;
$item->title = $request->title;
$item->save();
If you encounter the error message at the beginning, it may be because:
$request->title
May not have any data.
You can deal with this by checking the content using:
dd($request->title);
If this is null, consider how data can be entered into $request->title.
Summary
That's all for now.
I wrote an article about the error encountered in Laravel:
local.ERROR: Creating default object from empty value {“exception”:“[object] (ErrorException(code: 0): Creating default object from empty value at /app/Http/Controllers/PostController.php:30)
I hope this can be helpful to someone.
For feedback or complaints, please contact me via Twitter DM.
That's all!
Popular Articles
Deploying a PHP 7.4 + Laravel 6 Project to AWS EC2
Implementing Breadcrumbs in Laravel with laravel-breadcrumbs