Laravel faker Syntax

80 Views Asked by At

I am following a tutorial and I am trying to get faker to work to put in data in the Database. I am using this code.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Listing>
 */
class ListingFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition()
    {
        return [
            'title' => $this->faker->sentence(),
            // 'tags' => 'Laravel, API, Backend',
            // 'company' => $this->faker()->company(),
            // 'location' => $this->faker()->city(),
            // 'email' => $this->faker()->companyemail(),
            // 'website' => $this->faker()->url(),
            // 'description' => $this->faker()->paragraph(5),

        ];
    }
}

I am just limiting it to the title to try to figure out what my problem is. Here is the errors I am getting.

` INFO  Seeding database.


   Illuminate\Database\QueryException 

SQLSTATE[HY000]: General error: 1364 Field 'tags' doesn't have a default value (Connection: mysql, SQL: insert into `listings` (`title`, `updated_at`, `created_at`) values (Ea a voluptatem cum quidem eos aperiam., 2023-10-23 15:46:39, 2023-10-23 15:46:39))       

  at vendor\laravel\framework\src\Illuminate\Database\Connection.php:801
    797▕                     $this->getName(), $query, $this->prepareBindings($bindings), $e
    798▕                 );
    799▕             }
    800▕
  ➜ 801▕             throw new QueryException(       
    802▕                 $this->getName(), $query, $this->prepareBindings($bindings), $e
    803▕             );
    804▕         }
    805▕     }

  1   vendor\laravel\framework\src\Illuminate\Database\Connection.php:580
      PDOException::("SQLSTATE[HY000]: General error: 1364 Field 'tags' doesn't have a default value")    

  2   vendor\laravel\framework\src\Illuminate\Database\Connection.php:580
      PDOStatement::execute()`

I have tried to copy the code exactly but I can't find my error. Thanks in advance for your help.

I just wanted to seed the database with some bogus data for testing

1

There are 1 best solutions below

7
On BEST ANSWER

Unless the tags column is nullable, you need to pass it to create the model from a factory.

Listing::factory()->create(['tags' => 'Some, Tags, Here']);