Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$fillable doesn't work when creating model from seeder

Why when I create a model from a seeder I get the error(Illuminate\Database\QueryException):

SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint DETAIL: Failing row contains (null, aaa, aaaa, null, aaaa, null, 2021-04-14 13:18:16, 2021-04-14 13:18:16). (SQL: insert into "users" ("id", "name", "email", "password", "updated_at", "created_at") values (?, aaa, aaaa, aaaa, 2021-04-14 13:18:16, 2021-04-14 13:18:16) returning "id")

Seeder:


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    public function run()
    {
        $user = App\Models\User::create([
            'id' => null,
            'name' => 'aaa',
            'email' => 'aaaa',
            'password' => 'aaaa',
        ])->toArray();

        dump($user);
    }
}

Web route(it works):

Route::get('/', function () {
    // return view('welcome');

    $user = App\User::create([
        'id' => null,
        'name' => 'aaa',
        'email' => 'aaaa',
        'password' => 'aaaa',
    ])->toArray();

    dump($user);
});

A similar error occurs on Laravel ^7.28 and ^8.*(default installing).

I use PostgreSQL.

How fix it?

UPD:

class User extends Authenticatable
{
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}

I install the default laravel and run the default migrations by default. I am not making any additional changes.

like image 349
doox911 Avatar asked Sep 14 '26 18:09

doox911


1 Answers

Just use the following line before you execute the query.

\Illuminate\Database\Eloquent\Model::reguard();

Example:

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

class DatabaseSeeder extends Seeder
{
   public function run()
   {
    
      Model::reguard();

      // Your Create query here
       
   }
}
like image 78
black_belt Avatar answered Sep 18 '26 03:09

black_belt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!