How to use Slug in Laravel Factory

13 Jan 2019 . Tips and Tricks . 1.9K views

Today, I would love to show you a handy trick that, how to use Slug in the Laravel Factory. It's easy that you can call $faker->sentence to generate a sentence. However, making slug from that faker sentence is a bit tricky.

Imagine that, you have a migration file called CreatePostsTable that contains the following field-

Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->string('slug');
            $table->longText('description');
            $table->integer('user_id');
            $table->integer('publish');
            $table->string('photo')->nullable();
            $table->integer('counter');
            $table->timestamps();
        });

Now, Let's create a Post Factory. We can easily use $faker->sentence for the title and $faker->slug for the slug. In this case, the content for the $title and $slug may not be same.

In this situation, let's write the code in a bit tricky way.

<?php

use Faker\Generator as Faker;

$factory->define(App\Post::class, function (Faker $faker) {

    $title = $faker->sentence;
    $slug = str_slug($title, '-');

    return [
        'title' => $title,
        'slug' => $slug,
        'description' => $faker->paragraph,
        'user_id' => factory(App\User::class)->create()->id,
        'publish' => 1,
        'photo' => $faker->sha1,
        'counter' => 1
    ];
});

Now, if you generate the sentence from the factory, you will get the slug based on the title.

Hope it will help you. Thank you.