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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With