Sử dụng Factory trong Laravel 8

Hi mọi người, Bài viết này mình sẽ chia sẻ cách sử dụng factory tinker trong laravel 8. Như mọi người đã biết testing là một phần rất quan trọng của bất kỳ dự án phát triển web nào. Đôi khi chúng ta có yêu cầu phải thêm 100 hoặc 1000 dummy records(dữ liệu giả)

Hi mọi người,
Bài viết này mình sẽ chia sẻ cách sử dụng factory tinker trong laravel 8.
Như mọi người đã biết testing là một phần rất quan trọng của bất kỳ dự án phát triển web nào.
Đôi khi chúng ta có yêu cầu phải thêm 100 hoặc 1000 dummy records(dữ liệu giả) vào tables nào đó hoặc chức năng phân trang dữ liệu phải cần đến nhiều bản ghi để test.
Thay vì dùng tay để insert dummy records vào tables và mất nhiều thời gian để insert chúng.
Do đó, Laravel đã có chức năng tinker cái sẽ giúp chúng ta tạo nhiều dummy records trong table một cách nhanh chóng.
Mặc định trong ứng dụng laravel đã cung cấp sẵn User factory và bạn có thể tìm thấy nó trong url bên dưới:
url: database/factories/UserFactory.php.
Bạn có thể tạo một số bản ghi bằng cách sử dụng code bên dưới.

<?php

namespaceAppHttpControllers;useAppModelsUser;classUserControllerextendsController{publicfunctionindex(){User::factory()->count(5)->create();}}

Output:

Create Custom Factory:

Khi bạn muốn tạo các dummy records cho các tables như items , products or admin thì bạn phải tạo một new factory mới.
Ví dụ bên dưới mình sẽ tạo item factory và thực hiện insert 500 dummy records vào bảng items.
appModelsItem.php
Thêm code vào model như bên dưới

<?phpnamespaceAppModels;useIlluminateDatabaseEloquentFactoriesHasFactory;useIlluminateDatabaseEloquentModel;classItemextendsModel{useHasFactory;/**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */protected$fillable=['id','title','description',];}

Tiếp theo mở command và tạo item factory bằng command bên dưới.

php artisan make:factory ItemFactory --model=Item

Bây giờ new factory class cho item đã được tạo trong thư mục bên dưới.
databasefactoriesItemFactory.php
Hãy thêm code bên dưới vào file ItemFactory.php.

<?phpnamespaceDatabaseFactories;useAppModelsItem;useIlluminateDatabaseEloquentFactoriesFactory;useIlluminateSupportStr;classItemFactoryextendsFactory{/**
     * The name of the factory's corresponding model.
     *
     * @var string
     */protected$model=Item::class;/**
     * Define the model's default state.
     *
     * @return array
     */publicfunctiondefinition(){return['title'=>$this->faker->name,'description'=>$this->faker->text,];}}

Hàm definition() sẽ thêm dữ liệu mẫu tương ứng với trường title, description vào table items.
Sử dụng Faker, bạn có thể tạo các kiểu dữ liệu sau:

Numbers

Lorem text

Person i.e. titles, names, gender etc.

Addresses

Phone numbers

Companies

Text

DateTime

Internet i.e. domains, URLs, emails etc.

User Agents

Payments i.e. MasterCard

Colour

Files

Images

uuid

Barcodes

Cuối cùng hãy tạo và thêm code vào controller bên dưới để tạo 500 dummy records.
appHttpControllersItemController.php

<?phpnamespaceAppHttpControllers;useAppModelsItem;classItemControllerextendsController{/**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */publicfunctionindex(){Item::factory()->count(500)->create();}}

Output:
Bạn sẽ thấy 500 dummy records trên table items.

Hy vọng bài viết này có ích cho các bạn!

Nguồn: viblo.asia

Bài viết liên quan

7 Cách Tăng Tốc Ứng Dụng React Hiệu Quả Mà Bạn Có Thể Làm Ngay

React là một thư viện JavaScript phổ biến trong việc xây dựng giao diện người d

Trung Quốc “thả quân bài tẩy”: hàng loạt robot hình người!

MỘT CUỘC CÁCH MẠNG ROBOT ĐANG HÌNH THÀNH Ở TRUNG QUỐC Thượng Hải, ngày 13/5 –

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con