phplaravelsqlite

Laravel seeder dont fill table with foreing keys


I'm working on a Laravel project, and I have the following migrations:

public function up(): void
{
    Schema::create('customers', function (Blueprint $table) {
        $table->id('customer_id');
        $table->string('first_name', 50);
        $table->string('last_name', 50);
        $table->string('address', 100)->nullable();
        $table->string('phone', 15)->nullable();
        $table->string('email', 50)->unique();
        $table->timestamp('registration_date')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 */
public function down(): void
{
    Schema::dropIfExists('customers');
}
public function up(): void
{
    Schema::create('vehicles', function (Blueprint $table) {
        $table->id('vehicle_id');
        $table->foreignId('customer_id')->constrained('customers')->onDelete('cascade');
        $table->string('make', 50);
        $table->string('model', 50);
        $table->year('year');
        $table->string('license_plate', 15)->unique();
        $table->string('vin', 17)->unique();
        $table->string('color', 20)->nullable();
        $table->timestamp('registration_date')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 */
public function down(): void
{
    Schema::dropIfExists('vehicles');
}

As you can see in the vehicles table, there is a foreign key referencing the customers table. I'll show you the relationship in the models:

class Vehicle extends Model
{
    use HasFactory;

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'vehicle_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'customer_id',
        'make',
        'model',
        'year',
        'license_plate',
        'vin',
        'color',
        'registration_date',
    ];

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class, 'customer_id');
    }
}
class Customer extends Model
{
    use HasFactory;

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'customer_id';

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'first_name',
        'last_name',
        'address',
        'phone',
        'email',
        'registration_date',
    ];

    public function vehicles(): HasMany
    {
        return $this->hasMany(Vehicle::class, 'customer_id');
    }
}

And finally, the factories:

class CustomerFactory extends Factory
{
    protected $model = Customer::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'first_name' => fake()->name(),
            'last_name' => fake()->lastName(),
            'address' => fake()->address(),
            'phone' => fake()->phoneNumber(),
            'email' => fake()->email(),
            'registration_date' => fake()->date(),
        ];
    }
}

class VehicleFactory extends Factory
{
    protected $model = Vehicle::class;

    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'customer_id' => Customer::factory(),
            'make' => fake()->company,
            'model' => fake()->word,
            'year' => fake()->year,
            'license_plate' => strtoupper(fake()->unique()->bothify('???-####')),
            'vin' => strtoupper(fake()->unique()->bothify('?????????????????')),
            'color' => fake()->safeColorName,
            'registration_date' => fake()->date(),
        ];
    }
}

Apparently, the following error is occurring:

SQLSTATE[HY000]: General error: 1 foreign key mismatch - "vehicles" referencing "customers" (Connection: sqlite, SQL: insert into "vehicles" ("customer_id", "make", "model", "year", "license_plate", "vin", "color", "registration_date", "updated_at", "created_at") values (11, Wilderman Group, nostrum, 1970, VRF-4423, FVKRDKQWQHGDVFWBP, purple, 2019-01-16, 2024-11-13 18:30:33, 2024-11-13 18:30:33))

This error is due to the attempt to add a foreign key in the vehicles table for a customer with ID 11, which clearly does not exist because only 10 customers are created for 15 vehicles. I tried "forcing" the error to go away by looping through all the created vehicles and assigning them to existing customers, but that led to another error. I think there’s likely something wrong here that would be much simpler to fix than trying to solve it in a way the framework wasn't designed for. If anyone knows what might be wrong, I’d appreciate the help.

P.S. I’m using Laravel 11


Solution

  • I did this in a previous project and it worked. I will correct your code and show you. This is almost correct. Try it.

    public function up(): void
    {
     Schema::create('vehicles', function (Blueprint $table){
        $table->id('vehicle_id');
        $table->unsignedBigInteger('customer_id');
        $table->foreign('customer_id')->references('customer_id')->on('customers')->onDelete('cascade');
        $table->string('make', 50);
        $table->string('model', 50);
        $table->year('year');
        $table->string('license_plate', 15)->unique();
        $table->string('vin', 17)->unique();
        $table->string('color', 20)->nullable();
        $table->timestamp('registration_date')->default(DB::raw('CURRENT_TIMESTAMP'));
        $table->timestamps();
      }
    }
    

    now you can run a migration

    php artisan migrate:fresh --seed