How to use Slug in Laravel Factory

Tips and Tricks 13 Jan 2019

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) {

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.


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.