A
A
Anatoly2019-08-27 14:29:40
Laravel
Anatoly, 2019-08-27 14:29:40

Why does bulk save insert empty values?

Good afternoon!
Tell me, why can, with mass filling, a record is created, and all fields are empty?
Objects::create($request->all());
Although in the Objects model, bulk insertion is allowed
protected $guarded = [];

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konata Izumi, 2019-08-27
@les-anatoliy

I could not stand it and decided to check this case with a code.
PHP 7.3.3, Laravel 5.8
Migration:

class CreateTestTable extends Migration
{
    public function up()
    {
        Schema::create('test', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->nullable();
            $table->integer('age')->nullable();
            $table->timestamps();
        });
    }
}

Model:
class Test extends Model
{
    protected $table = 'test';
    protected $guarded = [];
}

php artisan tinker output
Psy Shell v0.9.9 (PHP 7.3.3 — cli) by Justin Hileman
>>> use App\Models\Test;
>>> Test::create(['age'=>'21','name'=>'Ivan']);
=> App\Models\Test {#2985
     age: "21",
     name: "Ivan",
     updated_at: "2019-08-27 12:44:11",
     created_at: "2019-08-27 12:44:11",
     id: 1,
   }

Remove the guard from the model:
class Test extends Model
{
    protected $table = 'test';
}

tinker:
Psy Shell v0.9.9 (PHP 7.3.3 — cli) by Justin Hileman
>>> use App\Models\Test;
>>> Test::create(['age'=>'24','name'=>'Ivan3']);
Illuminate/Database/Eloquent/MassAssignmentException with message 'Add [age] to fillable property to allow mass assignment on [App/Models/Test].'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question