In this example, I create laravel factory tinker. Laravel factory tinker is use to create fake or dummy data for laravel application. Laravel provide some of most important example laravel 8 factory tinker example.
If you create fresh project and you need to data at that time you can use laravel tinker factory. Laravel tinker factory is very important part of any web development project. Sometime we may require to add hundreds records in your posts table or maybe thousands of records.
Also, Laravel has tinker factory that provide to dummy records to your model table. So in laravel application you create Post model factory. So following step to create tinker factory and create dummy data in your laravel application.
Step 1: Install Laravel Apllication
First i install the laravel fresh project for create laravel post table tinker factory in your application. So following command to install laravel:
composer create-project --prefer-dist laravel/laravel blog
Step 2: Create Model and Migration
In this step we will create model and migration for posts table. Use the following command to create model and migration:
php artisan make:model Post -m
database/migrations/2021_02_03_095534_create_posts_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('detail'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } }
app/Models/Post.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'detail' ]; }
Step 3: Create Factory Tinker
In this step we will create Postfactory in the following command:
php artisan make:factory PostFactory --model=Post
Now open the database/factories/PostFactory.php and add the following code:
<?php namespace Database\Factories; use App\Models\Post; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Support\Str; class PostFactory extends Factory { /** * The name of the factory's corresponding model. * * @var string */ protected $model = Post::class; /** * Define the model's default state. * * @return array */ public function definition() { return [ 'name' => $this->faker->name, 'detail' => $this->faker->text, ]; } }
after run the following command in terminal
composer dump-autoload
and run the following command
php artisan tinker Post::factory()->count(5)->create()
I hope you understand laravel tinker factory and it can help you…