PHPackages                             jordan-price/laravel-faker-ai - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jordan-price/laravel-faker-ai

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

jordan-price/laravel-faker-ai
=============================

Laravel package that extends FakerPHP with AI-powered data generation

65PHP

Since Feb 27Pushed 1y ago1 watchersCompare

[ Source](https://github.com/jordan-price/laravel-faker-ai)[ Packagist](https://packagist.org/packages/jordan-price/laravel-faker-ai)[ RSS](/packages/jordan-price-laravel-faker-ai/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Laravel Faker AI
================

[](#laravel-faker-ai)

A Laravel package that extends FakerPHP by adding an AI-powered data generator using Prism, allowing you to generate more realistic and context-aware fake data in your Laravel applications. This package supports multiple AI providers including Ollama, OpenAI, Anthropic, and Mistral.

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require jordan-price/laravel-faker-ai
```

The package will automatically register its service provider if you're using Laravel's package auto-discovery.

Configuration
-------------

[](#configuration)

Next, execute the install command:

```
php artisan faker-ai:install
```

This will create a `config/faker-ai.php` configuration file in your project, which you can modify to your needs using environment variables.

Make sure you have your AI configuration set in your `.env` file:

```
# Choose your AI provider: ollama, openai, anthropic, or mistral
FAKER_AI_PROVIDER=ollama

# Model configuration for each provider
FAKER_OLLAMA_MODEL=llama3
FAKER_OPENAI_MODEL=gpt-3.5-turbo
FAKER_ANTHROPIC_MODEL=claude-3-sonnet-20240229
FAKER_MISTRAL_MODEL=mistral-tiny

# Caching configuration
FAKER_AI_ENABLE_CACHE=true
FAKER_AI_CACHE_TTL=1440

```

### Setting up Ollama Integration

[](#setting-up-ollama-integration)

This package provides built-in support for [Ollama](https://ollama.ai), allowing you to run AI models locally without relying on external APIs.

#### Prerequisites for Ollama

[](#prerequisites-for-ollama)

1. **Install Ollama**: Download and install from [ollama.ai](https://ollama.ai)
2. **Start the Ollama service**: Ensure it's running at `http://localhost:11434`
3. **Download a model**: Using the Ollama CLI, download a suitable model: ```
    ollama pull llama3
    ```

#### Required dependencies

[](#required-dependencies)

Make sure you have the Prism package installed:

```
composer require echolabsdev/prism
```

#### Ollama Configuration

[](#ollama-configuration)

Set these environment variables in your `.env` file:

```
FAKER_AI_PROVIDER=ollama
FAKER_OLLAMA_MODEL=llama3
FAKER_AI_ENABLE_CACHE=true
FAKER_AI_CACHE_TTL=1440

```

You can check available models on your Ollama instance with:

```
ollama list
```

#### Testing the Ollama Integration

[](#testing-the-ollama-integration)

To verify that Ollama is working correctly with your application:

```
// Create a simple test
$productName = fake()->promptAI('productName', context: [
    'product_type' => 'technology',
    'industry' => 'consumer electronics'
]);

echo "Generated product name: " . $productName;
```

#### Troubleshooting Ollama

[](#troubleshooting-ollama)

If you encounter issues:

1. **Verify Ollama is running**:

    ```
    curl http://localhost:11434/api/tags
    ```
2. **Check model availability**:

    ```
    ollama list
    ```
3. **Test direct API access**:

    ```
    curl -X POST http://localhost:11434/api/generate -d '{
      "model": "llama3",
      "prompt": "Generate a name for a smartphone"
    }'
    ```
4. **Enable debug logging** in your Laravel application:

    ```
    LOG_LEVEL=debug

    ```

Usage
-----

[](#usage)

The package adds a new `promptAI()` method to the Faker generator. You can use it in several ways:

### Basic Usage

[](#basic-usage)

```
$faker = app(\Faker\Generator::class);

// Generate a fake name using AI
$name = $faker->promptAI('name');

// Generate a movie review
$review = $faker->promptAI('movieReview');

// Generate a movie description
$description = $faker->promptAI('movieDescription');
```

You can also use the built-in `fake()` helper:

```
$name = fake()->promptAI('name');
```

### Using Specific Providers

[](#using-specific-providers)

You can specify which AI provider and model to use:

```
// Use OpenAI's GPT-4 model
$name = $faker->promptAI('name', provider: 'openai', model: 'gpt-4');

// Use Anthropic's Claude model
$description = $faker->promptAI('productDescription', provider: 'anthropic', model: 'claude-3-sonnet-20240229');

// Use Ollama's Llama model
$review = $faker->promptAI('movieReview', provider: 'ollama', model: 'llama3');
```

### Context-Aware Data Generation

[](#context-aware-data-generation)

One of the most powerful features of Laravel Faker AI is its ability to generate context-aware data. You can pass a context array to the `promptAI()` method to get data that's related to other properties:

```
// Generate a product description based on its name and category
$productName = 'Ergonomic Office Chair';
$productCategory = 'Office Furniture';

$description = $faker->promptAI(
    'productDescription',
    context: [
        'name' => $productName,
        'category' => $productCategory,
        'price' => '$199.99'
    ]
);

// Generate a blog post content based on its title and tags
$blogTitle = '10 Ways to Improve Your Productivity';
$blogTags = ['productivity', 'work-life balance', 'time management'];

$content = $faker->promptAI(
    'blogContent',
    context: [
        'title' => $blogTitle,
        'tags' => $blogTags,
        'audience' => 'professionals'
    ]
);
```

This is particularly useful in database seeders to create more realistic related content:

```
Product::factory()->create()->each(function ($product) use ($faker) {
    // Generate reviews that are specifically about this product
    Review::factory()->count(3)->create([
        'product_id' => $product->id,
        'content' => $faker->promptAI('productReview', context: [
            'product_name' => $product->name,
            'product_category' => $product->category,
            'rating' => rand(3, 5) // Generate mostly positive reviews
        ])
    ]);
});
```

### Generating Complete Objects at Once

[](#generating-complete-objects-at-once)

Rather than generating each field individually, you can use the `promptAIObject()` method to generate multiple fields for an object in a single API call:

```
// Generate multiple product fields at once
$productFields = fake()->promptAIObject(
    // List of fields to generate
    ['description', 'features', 'metaDescription', 'marketingSlogan'],
    // Context for all fields
    [
        'name' => 'Ultra HD Smart TV',
        'category' => 'Electronics',
        'price' => '$899.99'
    ]
);

// Create the product with all generated fields
$product = Product::create([
    'name' => 'Ultra HD Smart TV',
    'price' => 899.99,
    'category_id' => $category->id,
    'description' => $productFields['description'],
    'features' => $productFields['features'],
    'meta_description' => $productFields['metaDescription'],
    'slogan' => $productFields['marketingSlogan']
]);
```

This approach has several advantages:

- Makes a single API call instead of multiple calls
- Ensures consistency across all generated fields
- More efficient and faster for generating multiple related fields
- All fields have access to the same context information

You can also use this with Laravel's factories:

```
// Define a factory state that uses promptAIObject
public function withAIContent()
{
    return $this->state(function (array $attributes) {
        $name = $attributes['name'] ?? ucwords($this->faker->words(rand(2, 3), true));
        $category = Category::find($attributes['category_id'] ?? 1)->name ?? 'General';

        // Generate all content fields at once
        $aiContent = $this->faker->promptAIObject(
            ['description', 'features', 'metaDescription', 'marketingPoints'],
            [
                'name' => $name,
                'category' => $category,
                'price' => '$' . number_format($attributes['price'] ?? 99.99, 2)
            ]
        );

        // Merge the generated fields into the attributes
        return $aiContent;
    });
}
```

Usage in a seeder:

```
// Create a main brand and 5 contextually related sub-brands in a single step
Brand::factory()->createRelatedBrands(5)->create();
```

This creates a collection of brands that have a coherent theme and relationship with each other, rather than just random individual brands.

### Creating Complete Objects from Scratch with AI

[](#creating-complete-objects-from-scratch-with-ai)

For the ultimate simplicity, Laravel Faker AI can create **entire objects from scratch** with the `createAIObject()` method:

```
// Create a complete product with just a category
$product = fake()->createAIObject('Product', [
    'category' => 'Smartphones'
]);

// The AI will generate a complete product with all necessary fields
// $product = [
//     'name' => 'UltraPhone X15',
//     'description' => 'The UltraPhone X15 is a flagship smartphone...',
//     'price' => 899.99,
//     'features' => 'Triple camera, 5G connectivity, 6.5" display...',
//     'colors' => ['Black', 'Silver', 'Gold'],
//     'specifications' => ['CPU' => 'Octa-core', 'RAM' => '8GB'...],
//     ...and many more fields
// ]

// You can create the database record directly
Product::create($product);
```

This approach:

- Requires minimal input to generate complete, realistic objects
- AI determines appropriate fields based on the object type
- Creates consistent, related properties that make sense together
- Perfect for rapid prototyping and demo data generation

You can ensure specific fields are included:

```
// Require specific fields to be present
$blogPost = fake()->createAIObject(
    'BlogPost',
    ['topic' => 'Artificial Intelligence', 'audience' => 'beginners'],
    requiredFields: ['title', 'content', 'tags', 'readingTime', 'difficulty']
);

Post::create($blogPost);
```

And it integrates perfectly with Laravel factories:

```
// Define a factory that generates entire objects at once
public function definition()
{
    $category = Category::inRandomOrder()->first();

    // Let AI generate the entire product based on minimal info
    return $this->faker->createAIObject('Product', [
        'category' => $category->name,
        'price_range' => $this->faker->randomElement(['budget', 'mid-range', 'premium'])
    ]);
}
```

For even more simplicity in seeders:

```
// Generate 100 realistic products with just two lines of code
public function run()
{
    foreach (Category::all() as $category) {
        // Create 20 products per category, AI generates everything
        $products = collect(range(1, 20))->map(function() use ($category) {
            return fake()->createAIObject('Product', [
                'category' => $category->name
            ]);
        });

        // Bulk insert all products at once
        Product::insert($products->toArray());
    }
}
```

### Generating Multiple Related Objects in a Batch

[](#generating-multiple-related-objects-in-a-batch)

To generate multiple related objects that maintain context with each other, use the `createAIBatch()` method:

```
// Generate 5 related technology brands in a single API call
$brands = fake()->createAIBatch(
    'Brand',             // Type of object
    5,                   // Number to create
    [
        'industry' => 'Technology',
        'market' => 'consumer electronics'
    ]
);

// Each brand in the array will be contextually related to the others
// For example, they might all be smartphone manufacturers or all be software companies
// but each will be unique and make sense together as a collection

// You can then save all brands at once
Brand::insert($brands);
```

This approach is ideal for creating related sets of data, such as:

- A collection of products in the same category
- A set of related blog posts
- Multiple users from the same department
- A series of related events

Example with a Laravel factory:

```
