I’m building a job board project in Laravel, and I’m trying to establish a one-to-one relationship between User and Employer. However, my database table is not being generated correctly — the columns appear mismatched.
Here’s what I did:
Migration (database/migrations/xxxx_xx_xx_create_employers_table.php)
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('employers', function (Blueprint $table) {
$table->id();
$table->foreignIdFor(\App\Models\User::class);
$table->string('name');
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('employers');
}
};
But after running:
php artisan migrate:fresh --seed
My database table looks like this:
id | name | created_at | updated_at
1 | 2 | Company name | dates
The name column shows numbers instead of company names.
The created_at column contains company names instead of timestamps.
The user_id column is missing entirely, even though I used foreignIdFor.
EmployerFactory:
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class EmployerFactory extends Factory
{
public function definition(): array
{
return [
'name' => $this->faker->company(),
'user_id' => User::factory(),
];
}
}
DatabaseSeeder:
namespace Database\Seeders;
use App\Models\User;
use App\Models\Job;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
User::factory()->create([
'name' => 'Test User',
'email' => '[email protected]',
]);
Job::factory(100)->create();
}
}
I expected Laravel to create the employers table with the columns:
id | user_id | name | created_at | updated_at
and fill name with company names.
But instead, the data is misplaced, and the schema is incorrect. I’ve already tried:
php artisan migrate:fresh --seed- Deleting and recreating the database file
- Verifying that the migration matches the factory
Yet nothing changes.
What could cause Laravel to ignore or misapply the foreignIdFor() column and insert mismatched data into other columns?
I’m using Laravel 11, PHP 8.2
employerstable that's actually getting created doesn't haveuser_id(it only hasid, name, created_at, updated_at).