Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Laravel faker json


Laravel faker json


To generate valid JSON data using Laravel's Faker in a factory, you need to ensure that the data structure adheres to the expected JSON format, particularly when it comes to validation rules defined in your model.

Setting Up the Factory

In your factory, you can use the `Faker` instance to create a JSON structure that passes validation. Instead of using `json_encode`, which may lead to type mismatches, you should directly return an associative array that Laravel can automatically cast to JSON.

Here's how you can modify your factory:

php
use Illuminate\Database\Eloquent\Factories\Factory;

class ExampleFactory extends Factory
{
    protected $model = Example::class;

    public function definition()
    {
        return [
            'name' => $this->faker->words(3, true), // Generates a string of words
            'settings' => [
                'areas' => ['full', 'city'] // Directly return an array
            ],
        ];
    }
}

Model Configuration

Ensure that your model is properly set up to handle JSON data. You should have the `settings` attribute cast to an array in your model:

php
class Example extends Model
{
    protected $fillable = [
        'name',
        'settings'
    ];

    public static $rules = [
        'name' => 'required|string|max:255',
        'settings' => 'nullable|json'
    ];

    protected $casts = [
        'settings' => 'array' // Cast settings to array
    ];
}

Testing

When you create an instance of your model in a test, the `settings` attribute will automatically be converted into a JSON string when saved to the database, ensuring it meets the validation requirements. Here is how you might write a test:

php
/** @test */
public function shouldStore(): void
{
    $item = $this->model::factory()->make();
    $data = $item->toArray();

    $this->post(action([$this->controller, 'store']), $data)
        ->assertOk();
}

Conclusion

By returning an array directly in your factory for the `settings` field, you avoid issues with JSON encoding and type mismatches during validation. This method ensures that the data is correctly formatted as JSON when stored in the database, complying with your model's validation rules[1][2].

Citations:
[1] https://stackoverflow.com/questions/74345965/how-to-fake-valid-json-in-laravel
[2] https://laracasts.com/discuss/channels/laravel/seed-custom-json-field-in-a-factory
[3] https://laracasts.com/discuss/channels/general-discussion/fake-json-data-for-testing
[4] https://www.interserver.net/tips/kb/laravel-with-faker/
[5] https://github.com/bagisto/laravel-data-faker/blob/master/composer.json