Skip to content
Advertisement

Populate database table with Laravel Faker from pre-populated table

I want to populate a table with listings of car offers with dummy data.

The specific is that I want the make and model to be from a table already created in the database. Also the listing’s title to be Make and Model. My code is this, but I assume it is totally wrong:

public function definition()
{
    $id = DB::table('cars')->select('id')->inRandomOrder()->first();
    $make = DB::table('cars')->where('id', $id)->select('make')->first();
    $model = DB::table('cars')->where('id', $id)->select('model')->first();

    return [
        'title' => $make . " " . $model,
        'make' => $make,
        'model' => $model,
        'year' => $this->faker->numberBetween(1950, 2021),
        'slug' => $this->faker->word(),
    ];
}

Advertisement

Answer

The query builder in Laravel returns an object representing the database model when you fetch with first()

You should access the attributes when you’re setting them as other model attributes

return [
    'title' => $make->make . " " . $model->model,
    'make' => $make->make,
    'model' => $model->model,
    'year' => $this->faker->numberBetween(1950, 2021),
    'slug' => $this->faker->word(),
];

Note

The answer above only fixes the issue in the current code

The correct implementation would be to create models (if don’t exist already) and link them with relationships through foreign keys and then attach them together in a seeder

The factory should only contain a clear and clean definition of fake data

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement