DEV Community

Roby Cigar
Roby Cigar

Posted on • Edited on

Laravel 8 Notes Part 1 - Factory

Factory berguna untuk mengetest dengan cara populate database kita dengan data dummy atau data palsu.
Laravel menggunakan bantuan dari library FakerPHP/Faker.

Step 1 - Generate Factory File

php artisan make:factory NamaFactory
Enter fullscreen mode Exit fullscreen mode

Step 2 - Masukkan Faker Sesuai Atribut Model

<?php

namespace Database\Factories;

use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;

class CompanyFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Model::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $name = $this->faker->company;

        return [
            'user_id' => User::inRandomOrder()->first()->id,
            'name' => $name,
            'slug' => Str::slug($name, '-'),
            'phone_number' => $this->faker->phonenumber,
            'building_name' => $this->faker->buildingnumber,
            'street_address1' => $this->faker->StreetAddress,
            'city' => $this->faker->city,
            'country' => $this->faker->country,
            'postcode' => $this->faker->postcode,
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3 - Generate Data with Tinker

> php artisan tinker
App\Models\NamaModel::factory()->count(3)->make();
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay