# Tổng hợp những trường dữ liệu để facker, seeder, migration, migrate, factory full (ok)

### Generate primary key from group keys, Tạo khóa chính từ khóa nhóm

C:\xampp82\htdocs\lva2\database\migrations\2023\_10\_06\_020036\_create\_role\_user\_table.php

```php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('role_user', function (Blueprint $table) {
      $table->id();
      $table->unsignedInteger('role_id');
      $table->unsignedInteger('user_id');
      $table->primary(['role_id', 'user_id']);
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('role_user');
  }
};

```

### Facker slug

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FPCH5OC3XFNPJsd0vEC6u%2Fimage.png?alt=media&#x26;token=5dce282f-3f13-4fd8-87d8-b73a6e92e0fb" alt=""><figcaption></figcaption></figure>

C:\xampp82\htdocs\testvn\database\migrations\2023\_04\_17\_130047\_create\_posts\_table.php

```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('detail');
      $table->string('slug');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('posts');
  }
}

```

C:\xampp82\htdocs\testvn\database\factories\PostFactory.php

```php
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class PostFactory extends Factory
{
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition()
  {
    $detail = $this->faker->text(15);
    // $slug = str_slug($detail, '-');
    $slug = Str::slug($detail, '-');
    return [
      'detail'    => $detail,
      'slug'    => $slug
    ];
  }
}

```

### Cách thêm một cột vào một bảng cho trước

```
php artisan make:migration add_role_column_to_users_table
```

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddRoleColumnToUsersTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::table('users', function (Blueprint $table) {
      $table->enum('role',  ['user', 'manager', 'admin'])->default('user');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
  }
}
```

### Sử dụng $table->unique dưới dạng mảng

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2F79F0hBbh6kOKPjY7AfMI%2Fimage.png?alt=media&#x26;token=cf20a8d9-1fda-4b08-9a5d-ddebd2c44eb0" alt=""><figcaption></figcaption></figure>

C:\xampp82\htdocs\testcom\database\migrations\2023\_04\_04\_023335\_create\_roles\_table.php

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   */
  public function up(): void
  {
    Schema::create('roles', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('guard_name');
      $table->timestamps();
      $table->unique(['name','guard_name']);
    });
  }
  /**
   * Reverse the migrations.
   */
  public function down(): void
  {
    Schema::dropIfExists('roles');
  }
};

```

### Một cách sử dụng class tác riêng ra kết hợp  database\seeders\\[DatabaseSeeder.php](https://c-i-ph-n-m-m-tr-n-ubuntu-c-n-thi.gitbook.io/learn-lavarel/laravel-8-user-roles-and-permissions-and-product-crud-with-images-tutorial-ok)

C:\xampp82\htdocs\testfr\database\seeders\DatabaseSeeder.php

```php
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   */
  public function run(): void
  {
    // call others seeder class
    $this->call([
      PermissionTableSeeder::class,
      CreateAdminUserSeeder::class,
    ]);
  }
}

```

C:\xampp82\htdocs\testfr\database\seeders\PermissionTableSeeder.php

```php
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
class PermissionTableSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run(): void
  {
    $permissions = [
      'role-list',
      'role-create',
      'role-edit',
      'role-delete',
      'product-list',
      'product-create',
      'product-edit',
      'product-delete',
      'user-list',
      'user-create',
      'user-edit',
      'user-delete',
    ];
    foreach ($permissions as $permission) {
      Permission::create(['name' => $permission]);
    }
  }
}

```

C:\xampp82\htdocs\testfr\database\seeders\CreateAdminUserSeeder.php

```php
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
class CreateAdminUserSeeder extends Seeder
{
  /**
   * Run the database seeds.
   */
  public function run(): void
  {
    $user = User::create([
      'name' => 'Noor E Alam',
      'email' => 'admin@email.com',
      'password' => bcrypt('123456')
    ]);
    $role = Role::create(['name' => 'Admin']);
    $permissions = Permission::pluck('id', 'id')->all();
    $role->syncPermissions($permissions);
    $user->assignRole([$role->id]);
  }
}

```

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FbULnSfjkLPy5LwEi4WEG%2Fimage.png?alt=media&#x26;token=e6536f81-38f8-4f16-87f8-e5a73d9f8aed" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FkLD5tYTAfnRPBXiea6l2%2Fimage.png?alt=media&#x26;token=2a095028-8367-4f89-a7cf-52b5823785b8" alt=""><figcaption></figcaption></figure>

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FAqrSr9lnhOU2EeGehigW%2Fimage.png?alt=media&#x26;token=2d5d3c2b-ff57-4d81-ac58-049a8703a189" alt=""><figcaption></figcaption></figure>

### Sử dụng morphs thiết kế database :)

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('taggables', function (Blueprint $table) {
      $table->integer('tag_id');
      $table->morphs('taggable');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('taggables');
  }
};
p
```

### [**Một ví dụ sử dụng faker trực tiếp rất hay**](https://www.positronx.io/laravel-pagination-example-with-bootstrap-tutorial/)

C:\xampp\htdocs\datvietcoconut\database\seeders\DatabaseSeeder.php

```php
<?php
use Illuminate\Database\Seeder;
// Import DB and Faker services
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;
class DatabaseSeeder extends Seeder
{
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run()
  {
    $faker = Faker::create();
    foreach (range(1, 500) as $index) {
      DB::table('employees')->insert([
        'firstname' => $faker->firstname,
        'lastname' => $faker->lastname,
        'email' => $faker->email,
        'dob' => $faker->date($format = 'D-m-y', $max = '2010', $min = '1980')
      ]);
    }
  }
}
```

C:\xampp\htdocs\datvietcoconut\database\migrations\2022\_12\_09\_185509\_create\_employees\_table.php

```php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up()
  {
    Schema::create('employees', function (Blueprint $table) {
      $table->id();
      $table->string('firstname');
      $table->string('lastname');
      $table->string('email')->unique();
      $table->string('dob');
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down()
  {
    Schema::dropIfExists('employees');
  }
}
```

C:\xampp\htdocs\datvietcoconut\routes\web.php

```php
Route::get('/convert-to-json', function () {
  return Employee::paginate(5);
});
```

<figure><img src="https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2F6PO00GhNAfHfcI1vlyzS%2Fimage.png?alt=media&#x26;token=281f6d67-5c92-42ed-9ff7-0aa8909cc958" alt=""><figcaption></figcaption></figure>

## [Laravel Factory: Manual Increment of Column](https://stackoverflow.com/questions/44983693/laravel-factory-manual-increment-of-column), Number

```
class AliasCommandFactory extends Factory {

    private static $order = 1;

    protected $model = AliasCommand::class;

    public function definition() {
         $faker = $this->faker;
         return [
            'user_id' => User::inRandomOrder()->first()->id,
            'command' => $faker->word,
            'content' => $faker->sentence,
            'order'   => self::$order++
        ];
    }
}
```

## [Laravel 5.5 set size of integer fields in migration file](https://stackoverflow.com/questions/47987923/laravel-5-5-set-size-of-integer-fields-in-migration-file)

{% code overflow="wrap" %}

```php
$table->increments('id')->length(11);
$table->dateTime('created_time');
$table->integer('bank_id')->length(11);
$table->tinyInteger('is_black')->length(1);
```

{% endcode %}

### Length firstName 😒

```
'permission_id' => $this->faker->numberBetween(1, 30),
'permission_name' => $this->faker->firstName(10),
'created_at' => $this->faker->dateTime(),
'create_user' => $this->faker->firstName(10),
'deleted_at' =>$this->faker->dateTime(),
'delete_user' => $this->faker->firstName(10)
```

Nguồn 1: <https://github.com/fzaninotto/Faker>\
Nguồn 2: <https://viblo.asia/p/mot-so-thuoc-tinh-cua-thu-vien-faker-trong-laravel-bJzKmRVwZ9N>\
Nguồn 3: <https://stackoverflow.com/questions/43138197/laravel-faker-generate-gender-from-name>

Chú ý cách dùng:  migration

```
$faker = Faker\Factory::create();

$faker->name; // First and second name
$faker->randomDigit; // A random number
$faker->word; // A single word
$faker->sentence; // A sentence
$faker->unique()->word; // A single unique word
$faker->text($maxNbChars = 300); // 300 character long text
$faker->safeEmail; // An email address
$faker->hexcolor; // Hex color
```

**Dùng giá trị mặc định cho cột, default, enum**

C:\xampp\htdocs\reset\database\migrations\2022\_05\_20\_184747\_create\_products\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('products', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->enum('status', ['Pending', 'Wait', 'Active'])->default('Pending');
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('products');
  }
}
```

**Ví dụ 1: Cách tạo dữ liệu liên kết id tự động bằng migrage**

**Link:** [**https://github.com/alexeymezenin/laravel-realworld-example-app**](https://github.com/alexeymezenin/laravel-realworld-example-app)

**Factories**

C:\xampp\htdocs\laravel-realworld-example-app\database\factories\UserFactory.php

```
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory {
  public function definition() {
    return [
      'username' => $this->faker->name(),
      'email'    => $this->faker->unique()->safeEmail(),
      'password' => bcrypt('secret'),
      'image'    => $this->faker->imageUrl,
      'bio'      => $this->faker->text,
    ];
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\factories\ArticleFactory.php

```
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class ArticleFactory extends Factory {
  public function definition() {
    return [
      'user_id'     => User::factory(),
      'title'       => $this->faker->sentence,
      'slug'        => $this->faker->slug,
      'description' => $this->faker->text,
      'body'        => $this->faker->text,
    ];
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\factories\CommentFactory.php

```
<?php
namespace Database\Factories;
use App\Models\Article;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
class CommentFactory extends Factory {
  public function definition() {
    return [
      'user_id'    => User::factory(),
      'article_id' => Article::factory(),
      'body'       => $this->faker->text,
    ];
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\factories\TagFactory.php

```
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class TagFactory extends Factory {
  public function definition() {
    return [
      'name' => $this->faker->word,
    ];
  }
}
```

**Migrations**

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_11\_01\_164128\_create\_comments\_table.php

```
<?php
use App\Models\Article;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCommentsTable extends Migration {
  public function up() {
    Schema::create('comments', function (Blueprint $table) {
      $table->id();
      $table->foreignIdFor(User::class)->constrained()->onDelete('cascade');
      $table->foreignIdFor(Article::class)->constrained()->onDelete('cascade');
      $table->text('body');
      $table->timestamps();
    });
  }
  public function down() {
    Schema::dropIfExists('comments');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_11\_01\_115835\_create\_article\_user\_pivot\_table.php

```
<?php
use App\Models\Article;
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticleUserPivotTable extends Migration {
  public function up() {
    Schema::create('article_user', function (Blueprint $table) {
      $table->foreignIdFor(Article::class)->constrained()->onDelete('cascade');
      $table->foreignIdFor(User::class)->constrained()->onDelete('cascade');
      $table->index(['article_id', 'user_id']);
    });
  }
  public function down() {
    Schema::dropIfExists('article_user_pivot');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_11\_01\_110547\_create\_article\_tag\_pivot\_table.php

```
<?php
use App\Models\Article;
use App\Models\Tag;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticleTagPivotTable extends Migration {
  public function up() {
    Schema::create('article_tag', function (Blueprint $table) {
      $table->foreignIdFor(Article::class)->constrained()->onDelete('cascade');
      $table->foreignIdFor(Tag::class)->constrained()->onDelete('cascade');
      $table->index(['article_id', 'tag_id']);
    });
  }
  public function down() {
    Schema::dropIfExists('article_tag_pivot');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_11\_01\_105716\_create\_tags\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTagsTable extends Migration {
  public function up() {
    Schema::create('tags', function (Blueprint $table) {
      $table->id();
      $table->string('name')->unique();
      $table->index(['name']);
    });
  }
  public function down() {
    Schema::dropIfExists('tags');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_11\_01\_074539\_create\_articles\_table.php

```
<?php
use App\Models\User;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateArticlesTable extends Migration {
  public function up() {
    Schema::create('articles', function (Blueprint $table) {
      $table->id();
      $table->foreignIdFor(User::class)->constrained()->onDelete('cascade');
      $table->string('title');
      $table->string('slug');
      $table->string('description');
      $table->text('body');
      $table->timestamps();
      $table->index(['slug']);
    });
  }
  public function down() {
    Schema::dropIfExists('articles');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_10\_31\_180730\_create\_followers\_pivot\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFollowersPivotTable extends Migration {
  public function up() {
    Schema::create('followers', function (Blueprint $table) {
      $table->foreignId('follower_id')->constrained('users')->onDelete('cascade');
      $table->foreignId('following_id')->constrained('users')->onDelete('cascade');
      $table->index(['follower_id', 'following_id']);
    });
  }
  public function down() {
    Schema::dropIfExists('followers');
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021\_10\_31\_000000\_create\_users\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration {
  public function up() {
    Schema::create('users', function (Blueprint $table) {
      $table->id();
      $table->string('username')->unique();
      $table->string('email')->unique();
      $table->string('password');
      $table->string('image')->nullable();
      $table->text('bio')->nullable();
      $table->timestamps();
      $table->index(['username']);
    });
  }
  public function down() {
    Schema::dropIfExists('users');
  }
}
```

**Seeders**

```
<?php
namespace Database\Seeders;
use App\Models\User;
use App\Models\Article;
use App\Models\Comment;
use App\Models\Tag;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder {
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run() {
    Tag::factory(30)->create();
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\app\Models\Article.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;
class Article extends Model {
  use HasFactory;
  protected $fillable = ['title', 'description', 'body'];
  public function getRouteKeyName(): string {
    return 'slug';
  }
  public function user(): BelongsTo {
    return $this->belongsTo(User::class);
  }
  public function tags(): BelongsToMany {
    return $this->belongsToMany(Tag::class);
  }
  public function users(): BelongsToMany {
    return $this->belongsToMany(User::class);
  }
  public function comments(): HasMany {
    return $this->hasMany(Comment::class);
  }
  public function getFiltered(array $filters): Collection {
    return $this->filter($filters, 'tag', 'tags', 'name')
      ->filter($filters, 'author', 'user', 'username')
      ->filter($filters, 'favorited', 'users', 'username')
      ->when(array_key_exists('offset', $filters), function ($q) use ($filters) {
        $q->offset($filters['offset'])->limit($filters['limit']);
      })
      ->with('user', 'users', 'tags', 'user.followers')
      ->get();
  }
  public function scopeFilter($query, array $filters, string $key, string $relation, string $column) {
    return $query->when(array_key_exists($key, $filters), function ($q) use ($filters, $relation, $column, $key) {
      $q->whereRelation($relation, $column, $filters[$key]);
    });
  }
  public function setTitleAttribute(string $title): void{
    $this->attributes['title'] = $title;
    $this->attributes['slug'] = Str::slug($title);
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\app\Models\Comment.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Comment extends Model {
  use HasFactory;
  protected $fillable = ['body', 'article_id', 'user_id'];
  public function user(): BelongsTo {
    return $this->belongsTo(User::class);
  }
}
```

C:\xampp\htdocs\laravel-realworld-example-app\app\Models\Tag.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model {
  use HasFactory;
  public $timestamps = false;
  protected $fillable = ['name'];
}
```

C:\xampp\htdocs\laravel-realworld-example-app\app\Models\User.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject {
  use HasFactory;
  protected $fillable = ['username', 'email', 'password', 'bio', 'images'];
  protected $visible = ['username', 'email', 'bio', 'images'];
  public function getRouteKeyName(): string {
    return 'username';
  }
  public function articles(): HasMany {
    return $this->hasMany(Article::class);
  }
  public function favoritedArticles(): BelongsToMany {
    return $this->belongsToMany(Article::class);
  }
  public function followers(): BelongsToMany {
    return $this->belongsToMany(User::class, 'followers', 'following_id', 'follower_id');
  }
  public function following(): BelongsToMany {
    return $this->belongsToMany(User::class, 'followers', 'follower_id', 'following_id');
  }
  public function doesUserFollowAnotherUser(int $followerId, int $followingId): bool {
    return $this->where('id', $followerId)->whereRelation('following', 'id', $followingId)->exists();
  }
  public function doesUserFollowArticle(int $userId, int $articleId): bool {
    return $this->where('id', $userId)->whereRelation('favoritedArticles', 'id', $articleId)->exists();
  }
  public function setPasswordAttribute(string $password): void{
    $this->attributes['password'] = bcrypt($password);
  }
  public function getJWTIdentifier() {
    return $this->getKey();
  }
  public function getJWTCustomClaims() {
    return [];
  }
}
```

**Ví dụ 2**: <https://impulsivecode.com/laravel-8-pagination-example-with-bootstrap-4/>

Laravel 8 pagination Example with Bootstrap 4

June 24, 2021[Laravel](https://impulsivecode.com/laravel-8-pagination-example-with-bootstrap-4/)[Home](https://impulsivecode.com/)  »  [Laravel](https://impulsivecode.com/category/laravel/)  »   Laravel 8 pagination Example with Bootstrap 4

![](https://impulsivecode.com/wp-content/uploads/2021/06/Create-and-Export-CSV-file-in-Laravel-1.png)

###

Hey guys, in this tutorial I am going to cover how you can create the pagination in laravel 8 with the example of bootstrap 4.\
\
This is a step-by-step guide on laravel pagination example with Bootstrap 4 which is easy to follow. In this article, we are using articles as the example case and will paginate the articles.\
\
We will start off with setting up the laravel, then updating the DB credentials, creating model, migration and controller, connecting route with controller and creating the view, getting data from database and using `paginate` and `links` to create the pagination.\
\
So let’s get started.

### Step 1: Install Laravel

First of all, you need to install the laravel. I am installing the laravel in pagination folder.

```
composer create-project --prefer-dist laravel/laravel pagination
```

### Step 2: Update the ENV file and start server

In this step, you need to update the DB credentials in the `env` file and start the server by typing:

```
php artisan serve
```

### Step 3: Create Article model and migration

Now we will create the article model and its migration. For migration, we are using `-m` flag.

```
php artisan make:model article -m
```

### Step 4: Update the migrate function and run migration

We will add the `title` and `description` in the article migration `up` function in `database/migrations/create_articles_table.php`.

```
Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('description');
            $table->timestamps();
        });
```

Now we need to migrate the table we created.

```
php artisan migrate
```

### Step 5: Add the fake article data

You can skip this step if will add the data manually in the table.\
\
To add the dummy data we are using the seeders, so open up the `seeders/DatabaseSeeder.php` and update the `run` function to have the following code:

```
$faker= Faker::create();

        foreach (range(1,100) as $index){
            Article::create([
                'title'=>$faker->sentence(6),
                'description'=>$faker->paragraph(1),
            ]);
        }
```

We are using `Faker` to add the dummy title and description in the `Article` Table. `'title'=>$faker->sentence(6)` will add the 6 words as the title and `'description'=>$faker->paragraph(1)` will add 1 sentence as the description. We are adding 100 articles by doing that.\
\
Make sure to include the `use App\Models\Article;` `and use Faker\Factory as Faker;` in the header as well.\
\
To generate the data run command:

```
php artisan db:seed
```

### Step 6: Create Controller and Route

Run the following command to create `ArticleController`.

```
php artisan make:controller ArticleController
```

Place the following code in the `ArticleController`.

```
<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    //
    public function get_data(){
        $articles = Article::all();
        return view('home', compact('articles'));
    }

}
```

Now lets create the route in `routes/web.php` file.

```
Route::get('get_data',[\App\Http\Controllers\ArticleController::class,'get_data']);
```

### Step 7: Create View

Now create a blade file `resources/views/home.blade.php` and place the following code:

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-5">

    <h1 class="text-center">All the Articles</h1>

    <div class="row mt-5">
        @foreach($articles as $each_article)
            <div class="col-lg-4">
                <div class="card mt-2">
                    <div class="card-body">
                        <h5 class="card-title">{{$each_article->title}}</h5>
                        <p class="card-text">{{$each_article->description}}</p>
                    </div>
                </div>
            </div>
        @endforeach
    </div>
</div>

</body>
</html>
```

In this above `home` blade template, we have included the bootstrap and have used the card components to create the layout to show all the articles by traversing the `$articles` variable which we have passed from the `ArticleController`.\
\
If you open the browser and type `get_data` with the url on which your application is running you will see something like this.

![](https://impulsivecode.com/wp-content/uploads/2021/06/image-1024x577.png)

So at this point the articles are loading without any pagination. Lets convert it so that it will load with pagination.

### Step 8: Add the paginate in Controller

So in order to show articles with pagination we need to replace `Article::all();` to `Article::paginate(10);` in `ArticleController`.\
\
So our final controller code will look like:

```
<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    //
    public function get_data(){
        $articles = Article::paginate(10);
        return view('home', compact('articles'));
    }

}
```

Where `10` is number of articles we want to display per page. You can change this number as you like. For now I am sticking to `10` articles per page.

Now if you refresh the browser page you will see that only `10` articles are loading but there is no pagination.\
\
So next step is we need to add the links in the home.blade.php file as well.

### Step 9: Add the pagination links in the view file

So in the `resources/views/home.blade.php`, after the row div, we need to add `{!! $articles->links() !!}`.

So our final view file will look like this:

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container mt-5">

    <h1 class="text-center">All the Articles</h1>

    <div class="row mt-5">
        @foreach($articles as $each_article)
            <div class="col-lg-4">
                <div class="card mt-2">
                    <div class="card-body">
                        <h5 class="card-title">{{$each_article->title}}</h5>
                        <p class="card-text">{{$each_article->description}}</p>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    {!! $articles->links() !!}
</div>

</body>
</html>
```

So the final result will look like this:<br>

![](https://impulsivecode.com/wp-content/uploads/2021/06/image-2-1024x576.png)

As you can see that the pagination links but its not looking good. As there is no CSS for the pagination. You can either write custom css for that or you can use the `bootstrap` pagination.\
\
In order to use the `bootstrap` pagination, we need to add the `Paginator::useBootstrap();` in `boot()` function in `app/Providers/AppServiceProvider.php` .

So your `AppServiceProvider` file will look like this:

```
<?php

namespace App\Providers;

use Illuminate\Pagination\Paginator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Paginator::useBootstrap();
    }
}
```

And if you refresh the page, it will look like this:<br>

![](https://impulsivecode.com/wp-content/uploads/2021/06/image-3-1024x679.png)

Okay we are finally here just add the following `CSS` style in the head of the `home.blade.php` file.

```
<style>
        .pagination{
            float: right;
            margin-top: 10px;
        }
</style>
```

So the final `home.blade.php` will look like this:

```
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css">

    <style>
        .pagination{
            float: right;
            margin-top: 10px;
        }
    </style>
</head>
<body>
<div class="container mt-5">

    <h1 class="text-center">All the Articles</h1>

    <div class="row mt-5">
        @foreach($articles as $each_article)
            <div class="col-lg-4">
                <div class="card mt-2">
                    <div class="card-body">
                        <h5 class="card-title">{{$each_article->title}}</h5>
                        <p class="card-text">{{$each_article->description}}</p>
                    </div>
                </div>
            </div>
        @endforeach
    </div>

    {!! $articles->links() !!}
</div>

</body>
</html>
```

And if you refresh the browser it will look like this:

![](https://impulsivecode.com/wp-content/uploads/2021/06/image-4-1024x686.png)

Great 🙂 That’s it.\
Ví dụ 2:

```
1. Tạo Factory
$php artisan make:factory ItemFactory --model=Item
2. Tạo Seeder
$php artisan make:seeder CustomerSeeder
3. Chạy lệnh 
$php artisan db:seed --class=CustomerSeeder
```

C:\xampp\htdocs\api\database\factories\CustomerFactory.php

```
<?php
namespace Database\Factories;
use App\Models\Customer;
use Illuminate\Database\Eloquent\Factories\Factory;
class CustomerFactory extends Factory {
  /**
   * The name of the factory's corresponding model.
   *
   * @var string
   */
  protected $model = Customer::class;
  /**
   * Define the model's default state.
   *
   * @return array
   */
  public function definition() {
    return [
      'name_customer'    => $this->faker->userName,
      'phone_customer'   => $this->faker->phoneNumber,
      'address_customer' => $this->faker->address,
      'email_customer'   => $this->faker->safeEmail,
      'city_customer'    => $this->faker->city,
    ];
  }
}
```

C:\xampp\htdocs\api\database\seeders\CustomerSeeder.php

```
<?php
namespace Database\Seeders;
use App\Models\Customer;
use Illuminate\Database\Seeder;
class CustomerSeeder extends Seeder {
  /**
   * Run the database seeds.
   *
   * @return void
   */
  public function run() {
    Customer::factory()->count(5)->create();
  }
}
```

C:\xampp\htdocs\api\app\Models\Customer.php

```
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model {
  use HasFactory;
  public $timestamps = false;
  protected $table = 'customer';
  protected $primaryKey = 'id';
  protected $fillable = ['name_customer', 'phone_customer', 'address_customer','email_customer','city_customer'];
}
```

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2Fd7B6409agUOphT59SAnz%2FScreenshot_1.png?alt=media\&token=6ac0bd4f-2fb7-4f45-871a-fd1e19ed175d)

**Ví dụ 3: Một cách để tạo dữ liệu mới**

C:\xampp\htdocs\reset\database\migrations\2022\_05\_20\_090108\_create\_employees\_table.php

```
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('employees', function (Blueprint $table) {
      $table->id();
      $table->string('name');
      $table->string('email')->unique();
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('employees');
  }
}
```

C:\xampp\htdocs\reset\database\seeders\DatabaseSeeder.php

```
<?php
namespace Database\Seeders;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder {
  /**
   * Seed the application's database.
   *
   * @return void
   */
  public function run() {
    // \App\Models\User::factory(10)->create();
    $faker  = Faker::create();
    $gender = $faker->randomElement(['male', 'female']);
    foreach (range(1, 15) as $index) {
      DB::table('employees')->insert([
        'name'  => $faker->name($gender),
        'email' => $faker->email,
      ]);
    }
  }
}
```

![](https://1957079826-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MCBeDUD-PK_RF-YgJRe%2Fuploads%2FgKN3SD4Xxur5s4ZYbDgt%2FScreenshot_2.png?alt=media\&token=81f7ba8d-297e-4a72-9e8b-92ab0143f142)

## [Numbers and Strings](#numbers-and-strings) <a href="#numbers-and-strings" id="numbers-and-strings"></a>

## Numbers and Strings[#](https://fakerphp.github.io/formatters/numbers-and-strings/#numbers-and-strings) <a href="#numbers-and-strings" id="numbers-and-strings"></a>

### `randomDigit`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomdigit) <a href="#randomdigit" id="randomdigit"></a>

Generates a random integer from 0 until 9.

```php
echo $faker->randomDigit();

// an integer between 0 and 9
```

### `randomDigitNot`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomdigitnot) <a href="#randomdigitnot" id="randomdigitnot"></a>

Generates a random integer from 0 until 9, excluding a given number.

```php
echo $faker->randomDigitNot(2);

// 0, 1, 3, 4, 5, 6, 7, 8 or 9
```

### `randomDigitNotNull`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomdigitnotnull) <a href="#randomdigitnotnull" id="randomdigitnotnull"></a>

Generates a random integer from 1 until 9.

```php
echo $faker->randomDigitNotNull();

// an integer between 1 and 9
```

### `randomNumber`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomnumber) <a href="#randomnumber" id="randomnumber"></a>

Generates a random integer, containing between 0 and `$nbDigits` amount of digits. When the `$strict` parameter is `true`, it will only return integers with $nbDigits amount of digits.

```php
echo $faker->randomNumber(5, false);

// 123, 43, 19238, 5, or 1203

echo $faker->randomNumber(5, true);

// 12643, 42931, or 32919
```

### `randomFloat`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomfloat) <a href="#randomfloat" id="randomfloat"></a>

Generates a random float. Optionally it's possible to specify the amount of decimals.

The second and third parameters optionally specify a lower and upper bound respectively.

```php
echo $faker->randomFloat();

// 12.9830, 2193.1232312, 102.12

echo $faker->randomFloat(2);

// 43.23, 1203.49, 3428.93

echo $faker->randomFloat(1, 20, 30);

// 21.7, 27.2, 28.1
```

### `numberBetween`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#numberbetween) <a href="#numberbetween" id="numberbetween"></a>

Generates a random integer between `$min` and `$max`. By default, an integer is generated between `0` and `2,147,483,647` (32-bit integer).

```php
echo $faker->numberBetween();

// 120378987, 182, 102310983

echo $faker->numberBetween(0, 100);

// 32, 87, 91, 13, 75
```

### `randomLetter`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomletter) <a href="#randomletter" id="randomletter"></a>

Generates a random character from the alphabet.

```php
echo $faker->randomLetter();

// 'h', 'i', 'q'
```

### `randomElements`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomelements) <a href="#randomelements" id="randomelements"></a>

Returns `$count` amount of random element from the given array. By default, the `$count` parameter is set to 1.

```php
echo $faker->randomElements(['a', 'b', 'c', 'd', 'e']);

// ['c']

echo $faker->randomElements(['a', 'b', 'c', 'd', 'e'], 3);

// ['a', 'd', 'e']
```

### `randomElement`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomelement) <a href="#randomelement" id="randomelement"></a>

Returns a random element from the given array.

```php
echo $faker->randomElement(['a', 'b', 'c', 'd', 'e']);

// 'c'
```

### `randomKey`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#randomkey) <a href="#randomkey" id="randomkey"></a>

Returns a random key from the given array.

```php
echo $faker->randomKey(['a' => 1, 'b' => 2, 'c' => 3]);

// 'b'
```

### `shuffle`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#shuffle) <a href="#shuffle" id="shuffle"></a>

Returns a shuffled version of either an array or string.

```php
echo $faker->shuffle('hello-world');

// 'lrhoodl-ewl'

echo $faker->shuffle([1, 2, 3]);

// [3, 1, 2]
```

### `numerify`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#numerify) <a href="#numerify" id="numerify"></a>

Generate a string where all `#` characters are replaced by digits between 0 and 10. By default, `###` is used as input.

```php
echo $faker->numerify();

// '912', '271', '109', '674'

echo $faker->numerify('user-####');

// 'user-4928', 'user-3427', 'user-1280'
```

### `lexify`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#lexify) <a href="#lexify" id="lexify"></a>

Generate a string where all `?` characters are replaces with a random letter from the Latin alphabet. By default, `????` is used as input.

```php
echo $faker->lexify();

// 'sakh', 'qwei', 'adsj'

echo $faker->lexify('id-????');

// 'id-xoqe', 'id-pqpq', 'id-zpeu'
```

### `bothify`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#bothify) <a href="#bothify" id="bothify"></a>

Generate a string where `?` characters are replaced with a random letter, and `#` characters are replaces with a random digit between 0 and 10. By default, `## ??` is used as input.

```php
echo $faker->bothify();

// '46 hd', '19 ls', '75 pw'

echo $faker->bothify('?????-#####');

// 'lsadj-10298', 'poiem-98342', 'lcnsz-42938'
```

### `asciify`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#asciify) <a href="#asciify" id="asciify"></a>

Generate a string where `*` characters are replaced with a random character from the ASCII table. By default, `****` is used as input.

```php
echo $faker->asciify();

// '%Y+!', '{<"B', 'kF^a'

echo $faker->asciify('user-****');

// 'user-ntwx', 'user-PK`A', 'user-n`,X'
```

### `regexify`[#](https://fakerphp.github.io/formatters/numbers-and-strings/#regexify) <a href="#regexify" id="regexify"></a>

Generate a random string based on a regex. By default, an empty string is used as input.

```php
echo $faker->regexify();

// ''

echo $faker->regexify('[A-Z]{5}[0-4]{3}');

// 'DRSQX201', 'FUDPA404', 'CQVIU411'
```

## [Text and Paragraphs](https://fakerphp.github.io/formatters/text-and-paragraphs/) <a href="#text-and-paragraphs" id="text-and-paragraphs"></a>

### `word`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#word) <a href="#word" id="word"></a>

Generate a string containing random single word.

```php
echo $faker->word();

// 'molestiae', 'occaecati', 'distinctio'
```

### `words`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#words) <a href="#words" id="words"></a>

Generate an array containing a specified amount of random words.

Optionally, a second boolean parameter can be supplied. When `true`, a string will be returned instead of an array.

```php
echo $faker->words();

// ['praesentium', 'possimus', 'modi']

echo $faker->words(5);

// ['molestias', 'repellendus', 'qui', 'temporibus', 'ut']

echo $faker->words(3, true);

// 'placeat vero saepe'
```

### `sentence`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#sentence) <a href="#sentence" id="sentence"></a>

Generate a sentence containing a given amount of words. By default, `6` words is used.

Optionally, a second boolean parameter can be supplied. When `false`, only sentences with the given amount of words will be generated. By default, `sentence` will deviate from the given amount by +/- 40%.

```php
echo $faker->sentence();

// 'Sit vitae voluptas sint non voluptates.'

echo $faker->sentence(3);

// 'Laboriosam non voluptas.'
```

### `sentences`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#sentences) <a href="#sentences" id="sentences"></a>

Generate an array containing a given amount of sentences. By default, `3` sentences are generated.

Optionally, a second boolean parameter can be supplied. When `true`, a string will be returned instead of an array.

```php
echo $faker->sentences();

// ['Optio quos qui illo error.', 'Laborum vero a officia id corporis.', 'Saepe provident esse hic eligendi.']

echo $faker->sentences(2);

// ['Consequatur animi cumque.', 'Quibusdam eveniet ut.']
```

### `paragraph`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#paragraph) <a href="#paragraph" id="paragraph"></a>

Generate a paragraph of text, containing a given amount of sentences. By default, `3` sentences are generated.

Optionally, a second boolean parameter can be supplied. When `false`, only sentences with the given amount of words will be generated. By default, sentences will deviate from the default word length of 6 by +/- 40%.

```php
echo $faker->paragraph();

// 'Similique molestias exercitationem officia aut. Itaque doloribus et rerum voluptate iure. Unde veniam magni dignissimos expedita eius.'

echo $faker->paragraph(2);

// 'Consequatur velit incidunt ipsam eius beatae. Est omnis autem illum iure.'

echo $faker->paragraph(2, false);

// 'Laborum unde mollitia distinctio nam nihil. Quo expedita et exercitationem voluptas impedit.'
```

### `paragraphs`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#paragraphs) <a href="#paragraphs" id="paragraphs"></a>

Generate an array containing a given amount of paragraphs. By default, `3` paragraphs are generated.

Optionally, a second boolean parameter can be supplied. When `true`, a string will be returned instead of an array.

```php
echo $faker->paragraphs();

// [
//     'Aperiam fugiat alias nobis sunt hic. Quasi dolore autem quo sapiente et distinctio. Dolor ipsum saepe quaerat possimus molestiae placeat iste.', 
//     'Et enim labore debitis consequatur id omnis. Dolorum qui id natus tenetur doloremque sed. Delectus et quis sit quod. Animi assumenda dolorum voluptate nobis aut.',
//     'Voluptas quidem corporis non sed veritatis laudantium eaque modi. Quidem est et est deserunt. Voluptatem magni assumenda voluptas et qui delectus.'
// ]

echo $faker->paragraphs(2);

// [
//     'Quasi nihil nisi enim omnis natus eum. Autem sed ea a maxime. Qui eaque doloribus sit et ab repellat. Aspernatur est rem ut.',
//     'Corrupti quibusdam qui et excepturi. Fugiat minima soluta quae sunt. Aperiam adipisci quas minus eius.'
// ]

echo $faker->paragraphs(2, true);

// Quia odit et quia ab. Eos officia dolor aut quia et sed. Quis sint amet aut. Eius enim sint praesentium error quo sed eligendi. Quo id sint et amet dolorem rem maiores.
//
// Fuga atque velit consectetur id fugit eum. Cupiditate aut itaque dolores praesentium. Eius sunt ut ut ipsam.
```

### `text`[#](https://fakerphp.github.io/formatters/text-and-paragraphs/#text) <a href="#text" id="text"></a>

Generate a random string of text. The first parameter represents the maximum number of characters the text should contain (by default, `200`).

```php
echo $faker->text();

// Omnis accusantium non ut dolor modi. Quo vel omnis eum velit aspernatur pariatur. Blanditiis nisi accusantium a deleniti. Nam aut dolorum aut officiis consequatur.

echo $faker->text(100);

// Quaerat eveniet magni a optio. Officia facilis cupiditate fugiat earum ipsam nemo nulla.
```

## [Date and Time](https://fakerphp.github.io/formatters/date-and-time/) <a href="#date-and-time" id="date-and-time"></a>

## Date and Time[#](https://fakerphp.github.io/formatters/date-and-time/#date-and-time) <a href="#date-and-time" id="date-and-time"></a>

Methods accepting a `$timezone` argument default to `date_default_timezone_get()`. You can pass a custom timezone string to each method, or define a custom timezone for all time methods at once using `$faker::setDefaultTimezone($timezone)`.

### `unixTime`[#](https://fakerphp.github.io/formatters/date-and-time/#unixtime) <a href="#unixtime" id="unixtime"></a>

Generate an [unix time](https://en.wikipedia.org/wiki/Unix_time) between zero, and the given value. By default, `now` is used as input.

Optionally, a parameter can be supplied containing a `DateTime`, `int` or `string`.

```php
echo $faker->unixTime();

// 1605544623, 1025544612

echo $faker->unixTime(new DateTime('+3 weeks'));

// unix timestamp between 0 and the date 3 weeks from now.
```

### `dateTime`[#](https://fakerphp.github.io/formatters/date-and-time/#datetime) <a href="#datetime" id="datetime"></a>

Generate a `DateTime` between January 1, 1970, and the given max. By default, `now` is used as max.

Optionally, a parameter can be supplied containing a `DateTime`, `int` or `string`.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTime();

// DateTime: August 12, 1991 
```

### `dateTimeAD`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimead) <a href="#datetimead" id="datetimead"></a>

Generate a `DateTime` between January 1, 0001, and the given max. By default, `now` is used as max.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeAD();

// DateTime: September 19, 718
```

### `iso8601`[#](https://fakerphp.github.io/formatters/date-and-time/#iso8601) <a href="#iso8601" id="iso8601"></a>

Generate an ISO8601 formatted `string` between January 1, 0001, and the given max. By default, `now` is used as max.

```php
echo $faker->iso8601();
```

### `date`[#](https://fakerphp.github.io/formatters/date-and-time/#date) <a href="#date" id="date"></a>

Generate a date `string`, with a given format and max value. By default, `'Y-m-d'` and `'now'` are used for the format and maximum value respectively.

```php
echo $faker->date();

// '1999-06-09'

echo $faker->date('Y_m_d');

// '2011_02_19'
```

### `time`[#](https://fakerphp.github.io/formatters/date-and-time/#time) <a href="#time" id="time"></a>

Generate a time `string`, with a given format and max value. By default, `H:i:s'` and `now` are used for the format and maximum value respectively.

```php
echo $faker->time();

// '12:02:50'

echo $faker->time('H_i_s');

// '20_49_12'
```

### `dateTimeBetween`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimebetween) <a href="#datetimebetween" id="datetimebetween"></a>

Generate a `DateTime` between two dates. By default, `-30 years` and `now` are used.

An optional third parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeBetween();

// a date between -30 years ago, and now

echo $faker->dateTimeBetween('-1 week', '+1 week');

// a date between -1 week ago, and 1 week from now
```

### `dateTimeInInterval`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimeininterval) <a href="#datetimeininterval" id="datetimeininterval"></a>

Generate a `DateTime` between a date and an interval from that date. By default, the date is set to `-30 years`, and the interval is set to `+5 days`.

An optional third parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeInInterval();

// a date between -30 years ago, and -30 years + 5 days

echo $faker->dateTimeInInterval('-1 week', '+3 days');

// a date between -1 week ago, and -1 week + 3 days
```

### `dateTimeThisCentury`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimethiscentury) <a href="#datetimethiscentury" id="datetimethiscentury"></a>

Generate a `DateTime` that is within the current century. An optional `$max` value can be supplied, by default this is set to `now`.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeThisCentury();

// a date somewhere in this century

echo $faker->dateTimeThisCentury('+8 years');

// a date somewhere in this century, with an upper bound of +8 years
```

### `dateTimeThisDecade`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimethisdecade) <a href="#datetimethisdecade" id="datetimethisdecade"></a>

Generate a `DateTime` that is within the current decade. An optional `$max` value can be supplied, by default this is set to `now`.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeThisDecade();

// a date somewhere in this decade

echo $faker->dateTimeThisDecade('+2 years');

// a date somewhere in this decade, with an upper bound of +2 years
```

### `dateTimeThisYear`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimethisyear) <a href="#datetimethisyear" id="datetimethisyear"></a>

Generate a `DateTime` that is within the current year. An optional `$max` value can be supplied, by default this is set to `now`.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeThisYear();

// a date somewhere in this year

echo $faker->dateTimeThisYear('+2 months');

// a date somewhere in this year, with an upper bound of +2 months
```

### `dateTimeThisMonth`[#](https://fakerphp.github.io/formatters/date-and-time/#datetimethismonth) <a href="#datetimethismonth" id="datetimethismonth"></a>

Generate a `DateTime` that is within the current month. An optional `$max` value can be supplied, by default this is set to `now`.

An optional second parameter can be supplied, with the timezone.

```php
echo $faker->dateTimeThisMonth();

// a date somewhere in this month

echo $faker->dateTimeThisMonth('+12 days');

// a date somewhere in this month, with an upper bound of +12 days
```

### `amPm`[#](https://fakerphp.github.io/formatters/date-and-time/#ampm) <a href="#ampm" id="ampm"></a>

Generate a random `DateTime`, with a given upper bound, and return the am/pm `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->amPm();

// 'am'

echo $faker->amPm('+2 weeks');

// 'pm'
```

### `dayOfMonth`[#](https://fakerphp.github.io/formatters/date-and-time/#dayofmonth) <a href="#dayofmonth" id="dayofmonth"></a>

Generate a random `DateTime`, with a given upper bound, and return the day of month `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->dayOfMonth();

// '24'

echo $faker->dayOfMonth('+2 weeks');

// '05'
```

### `dayOfWeek`[#](https://fakerphp.github.io/formatters/date-and-time/#dayofweek) <a href="#dayofweek" id="dayofweek"></a>

Generate a random `DateTime`, with a given upper bound, and return the day of week `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->dayOfWeek();

// 'Tuesday'

echo $faker->dayOfWeek('+2 weeks');

// 'Friday'
```

### `month`[#](https://fakerphp.github.io/formatters/date-and-time/#month) <a href="#month" id="month"></a>

Generate a random `DateTime`, with a given upper bound, and return the month's number `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->month();

// '9'

echo $faker->month('+10 weeks');

// '7'
```

### `monthName`[#](https://fakerphp.github.io/formatters/date-and-time/#monthname) <a href="#monthname" id="monthname"></a>

Generate a random `DateTime`, with a given upper bound, and return the month's name `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->monthName();

// 'September'

echo $faker->monthName('+10 weeks');

// 'April'
```

### `year`[#](https://fakerphp.github.io/formatters/date-and-time/#year) <a href="#year" id="year"></a>

Generate a random `DateTime`, with a given upper bound, and return the year's `string` value. By default, the upper bound is set to `now`.

```php
echo $faker->year();

// '1998'

echo $faker->year('+10 years');

// '2022'
```

### `century`[#](https://fakerphp.github.io/formatters/date-and-time/#century) <a href="#century" id="century"></a>

Generate a random century name.

```php
echo $faker->century();

// 'IX', 'XVII', 'II'
```

### `timezone`[#](https://fakerphp.github.io/formatters/date-and-time/#timezone) <a href="#timezone" id="timezone"></a>

Generate a random timezone name.

```php
echo $faker->timezone();

// 'Europe/Amsterdam', 'America/Montreal'

echo $faker->timezone('US');

// 'America/New_York', 'America/Los_Angeles'
```

## [Internet](https://fakerphp.github.io/formatters/internet/) <a href="#internet" id="internet"></a>

## Internet[#](https://fakerphp.github.io/formatters/internet/#internet) <a href="#internet" id="internet"></a>

### `email`[#](https://fakerphp.github.io/formatters/internet/#email) <a href="#email" id="email"></a>

Generate an email address.

```php
echo $faker->email();

// 'orval.treutel@blick.com', 'hickle.lavern@erdman.com'
```

### `safeEmail`[#](https://fakerphp.github.io/formatters/internet/#safeemail) <a href="#safeemail" id="safeemail"></a>

Generate a safe email address.

```php
echo $faker->safeEmail();

// 'spencer.ricardo@example.com', 'wolf.sabryna@example.org'
```

### `freeEmail`[#](https://fakerphp.github.io/formatters/internet/#freeemail) <a href="#freeemail" id="freeemail"></a>

Generate a free email address (free, as in, free sign-up).

```php
echo $faker->freeEmail();

// 'marcelino.hyatt@yahoo.com', 'abby81@gmail.com'
```

### `companyEmail`[#](https://fakerphp.github.io/formatters/internet/#companyemail) <a href="#companyemail" id="companyemail"></a>

Generate a company email.

```php
echo $faker->companyEmail();

// 'hschinner@reinger.net', 'paula.blick@hessel.com'
```

### `freeEmailDomain`[#](https://fakerphp.github.io/formatters/internet/#freeemaildomain) <a href="#freeemaildomain" id="freeemaildomain"></a>

Generate a free email domain name.

```php
echo $faker->freeEmailDomain();

// 'gmail.com', 'hotmail.com'
```

### `safeEmailDomain`[#](https://fakerphp.github.io/formatters/internet/#safeemaildomain) <a href="#safeemaildomain" id="safeemaildomain"></a>

Generate a safe email domain.

```php
echo $faker->safeEmailDomain();

// 'example.net', 'example.org'
```

### `userName`[#](https://fakerphp.github.io/formatters/internet/#username) <a href="#username" id="username"></a>

Generate a username.

```php
echo $faker->userName();

// 'ipaucek', 'homenick.alexandre'
```

### `password`[#](https://fakerphp.github.io/formatters/internet/#password) <a href="#password" id="password"></a>

Generate a password, with a given minimum and maximum length. By default, the values `6` and `20` are used for the minimum and maximum respectively.

```php
echo $faker->password();

// 'dE1U[G$n4g%-Eie[]rn[', '-YCc1t|NSh)U&j6Z'

echo $faker->password(2, 6);

// 'GK,M|', '/ZG.'
```

### `domainName`[#](https://fakerphp.github.io/formatters/internet/#domainname) <a href="#domainname" id="domainname"></a>

Generate a domain name.

```php
echo $faker->domainName();

// 'toy.com', 'schamberger.biz'
```

### `domainWord`[#](https://fakerphp.github.io/formatters/internet/#domainword) <a href="#domainword" id="domainword"></a>

Generate a domain word.

```php
echo $faker->domainWord();

// 'feil', 'wintheiser'
```

### `tld`[#](https://fakerphp.github.io/formatters/internet/#tld) <a href="#tld" id="tld"></a>

Generate a tld (top-level domain).

```php
echo $faker->tld();

// 'com', 'org'
```

### `url`[#](https://fakerphp.github.io/formatters/internet/#url) <a href="#url" id="url"></a>

Generate a URL.

```php
echo $faker->url();

// 'http://cormier.info/eligendi-rem-omnis-quia.html', 'http://pagac.com/'
```

### `slug`[#](https://fakerphp.github.io/formatters/internet/#slug) <a href="#slug" id="slug"></a>

Generate a slug, with a given amount of words. By default, the amount of words it set to 6.

Optionally, a second parameter can be supplied. When `false`, only slugs with the given amount of words will be generated.

```php
echo $faker->slug();

// 'facere-ipsam-sit-aut-ut-dolorem', 'qui-soluta-sed-facilis-est-ratione-dolor-autem'

echo $faker->slug(2);

// 'et-et-et', 'temporibus-iure'

echo $faker->slug(3, false);

// 'ipsa-consectetur-est', 'quia-ad-nihil'
```

### `ipv4`[#](https://fakerphp.github.io/formatters/internet/#ipv4) <a href="#ipv4" id="ipv4"></a>

Generate an IPv4 address.

```php
echo $faker->ipv4();

// '90.119.172.201', '84.172.232.19'
```

### `localIpv4`[#](https://fakerphp.github.io/formatters/internet/#localipv4) <a href="#localipv4" id="localipv4"></a>

Generate an IPv4 address, inside a local subnet.

```php
echo $faker->localIpv4();

// '192.168.85.208', '192.168.217.138'
```

### `ipv6`[#](https://fakerphp.github.io/formatters/internet/#ipv6) <a href="#ipv6" id="ipv6"></a>

Generate an IPv6 address.

```php
echo $faker->ipv6();

// 'c3f3:40ed:6d6c:4e8e:746b:887a:4551:42e5', '1c3d:a2cf:80ad:f2b6:7794:4f3f:f9fb:59cf'
```

### `macAddress`[#](https://fakerphp.github.io/formatters/internet/#macaddress) <a href="#macaddress" id="macaddress"></a>

Generate a random MAC address.

```php
echo $faker->macAddress();

// '94:00:10:01:58:07', '0E:E1:48:29:2F:E2'
```

## [User Agent](https://fakerphp.github.io/formatters/user-agent/) <a href="#user-agent" id="user-agent"></a>

### `userAgent`[#](https://fakerphp.github.io/formatters/user-agent/#useragent) <a href="#useragent" id="useragent"></a>

Generate a user agent.

```php
echo $faker->userAgent();

// 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/5350 (KHTML, like Gecko) Chrome/37.0.806.0 Mobile Safari/5350'
```

### `chrome`[#](https://fakerphp.github.io/formatters/user-agent/#chrome) <a href="#chrome" id="chrome"></a>

Generate a user agent that belongs to Google Chrome.

```php
echo $faker->chrome();

// 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_8_1) AppleWebKit/5352 (KHTML, like Gecko) Chrome/40.0.848.0 Mobile Safari/5352'
```

### `firefox`[#](https://fakerphp.github.io/formatters/user-agent/#firefox) <a href="#firefox" id="firefox"></a>

Generate a user agent that belongs to Mozilla Firefox.

```php
echo $faker->firefox();

// 'Mozilla/5.0 (X11; Linux i686; rv:7.0) Gecko/20121220 Firefox/35.0'
```

### `safari`[#](https://fakerphp.github.io/formatters/user-agent/#safari) <a href="#safari" id="safari"></a>

Generate a user agent that belongs to Apple Safari.

```php
echo $faker->safari();

// 'Mozilla/5.0 (Macintosh; PPC Mac OS X 10_8_3 rv:5.0; sl-SI) AppleWebKit/532.33.2 (KHTML, like Gecko) Version/5.0 Safari/532.33.2'
```

### `opera`[#](https://fakerphp.github.io/formatters/user-agent/#opera) <a href="#opera" id="opera"></a>

Generate a user agent that belongs to Opera.

```php
echo $faker->opera();

// 'Opera/8.55 (Windows 95; en-US) Presto/2.9.286 Version/11.00'
```

### `internetExplorer`[#](https://fakerphp.github.io/formatters/user-agent/#internetexplorer) <a href="#internetexplorer" id="internetexplorer"></a>

Generate a user agent that belongs to Internet Explorer.

```php
echo $faker->internetExplorer();

// 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 5.0; Trident/5.1)'
```

### `msedge`[#](https://fakerphp.github.io/formatters/user-agent/#msedge) <a href="#msedge" id="msedge"></a>

Generate a user agent that belongs to Microsoft Ege.

```php
echo $faker->msedge();

// 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.82 Safari/537.36 Edg/99.0.1150.36'
```

## [Payment](#payment) <a href="#payment" id="payment"></a>

## &#x20;<a href="#payment" id="payment"></a>

### `creditCardType`[#](https://fakerphp.github.io/formatters/payment/#creditcardtype) <a href="#creditcardtype" id="creditcardtype"></a>

Generate a credit card type.

```php
echo $faker->creditCardType();

// 'MasterCard', 'Visa'
```

### `creditCardNumber`[#](https://fakerphp.github.io/formatters/payment/#creditcardnumber) <a href="#creditcardnumber" id="creditcardnumber"></a>

Generate a credit card number with a given type. By default, a random type is used. Supported types are 'Visa', ' MasterCard', 'American Express', and 'Discover'.

Optionally, a second and third parameter may be supplied. These define if the credit card number should be formatted, and which separator to use.

```php
echo $faker->creditCardNumber();

// '4556817762319090', '5151791946409422'

echo $faker->creditCardNumber('Visa');

// '4539710900519030', '4929494068680706'

echo $faker->creditCardNumber('Visa', true);

// '4624-6303-5483-5433', '4916-3711-2654-8734'

echo $faker->creditCardNumber('Visa', true, '::');

// '4539::6626::9844::3867', '4916::6161::0683::7022'
```

### `creditCardExpirationDate`[#](https://fakerphp.github.io/formatters/payment/#creditcardexpirationdate) <a href="#creditcardexpirationdate" id="creditcardexpirationdate"></a>

Generate a credit card expiration date (`DateTime`). By default, only valid dates are generated. Potentially invalid dates can be generated by using `false` as input.

```php
echo $faker->creditCardExpirationDate();

// DateTime: between now and +36 months

echo $faker->creditCardExpirationDate(false);

// DateTime: between -36 months and +36 months
```

### `creditCardExpirationDateString`[#](https://fakerphp.github.io/formatters/payment/#creditcardexpirationdatestring) <a href="#creditcardexpirationdatestring" id="creditcardexpirationdatestring"></a>

Generate a credit card expiration date (`string`). By default, only valid dates are generated. Potentially invalid dates can be generated by using `false` as input.

The string is formatted using `m/y`. Optionally, a second parameter can be passed to override this format.

```php
echo $faker->creditCardExpirationDateString();

// '09/23', '06/21'

echo $faker->creditCardExpirationDateString(false);

// '01/18', '09/21'

echo $faker->creditCardExpirationDateString(true, 'm-Y');

// '12-2020', '07-2023'
```

### `creditCardDetails`[#](https://fakerphp.github.io/formatters/payment/#creditcarddetails) <a href="#creditcarddetails" id="creditcarddetails"></a>

Generate an `array` with credit card details. By default, only valid expiration dates will be generated. Potentially invalid expiration dates can be generated by using `false` as input.

```php
echo $faker->creditCardDetails();

// ['type' => 'Visa', 'number' => '4961616159985979', 'name' => 'Mr. Charley Greenfelder II', 'expirationDate' => '01/23']

echo $faker->creditCardDetails(false);

// ['type' => 'MasterCard', 'number' => '2720381993865020', 'name' => 'Dr. Ivy Gerhold Jr.', 'expirationDate' => '10/18']
```

### `iban`[#](https://fakerphp.github.io/formatters/payment/#iban) <a href="#iban" id="iban"></a>

Generate an `IBAN` string with a given country and bank code. By default, a random country and bank code will be used.

The country code format should be [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).

```php
echo $faker->iban();

// 'LI2690204NV3C0BINN164', 'NL56ETEE3836179630'

echo $faker->iban('NL');

// 'NL95ZOGL3572193597', 'NL76LTTM8016514526'

echo $faker->iban('NL', 'INGB');

// 'NL11INGB2348102199', 'NL87INGB6409935479'
```

### `swiftBicNumber`[#](https://fakerphp.github.io/formatters/payment/#swiftbicnumber) <a href="#swiftbicnumber" id="swiftbicnumber"></a>

Generate a random [SWIFT/BIC](https://en.wikipedia.org/wiki/ISO_9362) number `string`.

```php
echo $faker->swiftBicNumber();

// 'OGFCTX2GRGN', 'QFKVLJB7'
```

## [Color](https://fakerphp.github.io/formatters/color/) <a href="#color" id="color"></a>

## &#x20;<a href="#color" id="color"></a>

### `hexColor`[#](https://fakerphp.github.io/formatters/color/#hexcolor) <a href="#hexcolor" id="hexcolor"></a>

Generate a random hex color.

```php
$faker->hexColor();

// '#ccd578', '#fafa11', '#ea3781'
```

### `safeHexColor`[#](https://fakerphp.github.io/formatters/color/#safehexcolor) <a href="#safehexcolor" id="safehexcolor"></a>

Generate a random hex color, containing only 16 values per R, G and B.

```php
$faker->safeHexColor();

// '#00eecc', '#00ff88', '#00aaee'
```

### `rgbColorAsArray`[#](https://fakerphp.github.io/formatters/color/#rgbcolorasarray) <a href="#rgbcolorasarray" id="rgbcolorasarray"></a>

Generate a random RGB color, as an `array`.

```php
$faker->rgbColorAsArray();

// [0 => 30, 1 => 22, 2 => 177], [0 => 150, 1 => 55, 2 => 34], [0 => 219, 1 => 253, 2 => 248]
```

### `rgbColor`[#](https://fakerphp.github.io/formatters/color/#rgbcolor) <a href="#rgbcolor" id="rgbcolor"></a>

Generate a comma-separated RGB color `string`.

```php
$faker->rgbColor();

// '105,224,78', '97,249,98', '24,250,221'
```

### `rgbCssColor`[#](https://fakerphp.github.io/formatters/color/#rgbcsscolor) <a href="#rgbcsscolor" id="rgbcsscolor"></a>

Generate a CSS-friendly RGB color `string`.

```php
$faker->rgbCssColor();

// 'rgb(9,110,101)', 'rgb(242,133,147)', 'rgb(124,64,0)'
```

### `rgbaCssColor`[#](https://fakerphp.github.io/formatters/color/#rgbacsscolor) <a href="#rgbacsscolor" id="rgbacsscolor"></a>

Generate a CSS-friendly RGBA (alpha channel) color `string`.

```php
$faker->rgbaCssColor();

// 'rgba(179,65,209,1)', 'rgba(121,53,231,0.4)', 'rgba(161,239,152,0.9)'
```

### `safeColorName`[#](https://fakerphp.github.io/formatters/color/#safecolorname) <a href="#safecolorname" id="safecolorname"></a>

Generate a CSS-friendly color name.

```php
$faker->safeColorName();

// 'white', 'fuchsia', 'purple'
```

### `colorName`[#](https://fakerphp.github.io/formatters/color/#colorname) <a href="#colorname" id="colorname"></a>

Generate a CSS-friendly color name.

```php
$faker->colorName();

// 'SeaGreen', 'Crimson', 'DarkOliveGreen'
```

### `hslColor`[#](https://fakerphp.github.io/formatters/color/#hslcolor) <a href="#hslcolor" id="hslcolor"></a>

Generate a random HSL color `string`.

```php
$faker->hslColor();

// '87,10,25', '94,24,27', '207,68,84'
```

### `hslColorAsArray`[#](https://fakerphp.github.io/formatters/color/#hslcolorasarray) <a href="#hslcolorasarray" id="hslcolorasarray"></a>

Generate a random HSL color, as an `array`.

```php
$faker->hslColorAsArray();

// [0 => 311, 1 => 84, 2 => 31], [0 => 283, 1 => 85, 2 => 49], [0 => 57, 1 => 48, 2 => 36]
```

## [File](https://fakerphp.github.io/formatters/file/) <a href="#file" id="file"></a>

## &#x20;<a href="#file" id="file"></a>

### `mimeType`[#](https://fakerphp.github.io/formatters/file/#mimetype) <a href="#mimetype" id="mimetype"></a>

Generate a random MIME-type `string`.

```php
$faker->mimeType();

// 'application/vnd.ms-artgalry', 'application/mods+xml', 'video/x-sgi-movie'
```

### `fileExtension`[#](https://fakerphp.github.io/formatters/file/#fileextension) <a href="#fileextension" id="fileextension"></a>

Generate a random file extension type `string`.

```php
$faker->fileExtension();

// 'deb', 'mp4s', 'uvg'
```

### `file`[#](https://fakerphp.github.io/formatters/file/#file_1) <a href="#file_1" id="file_1"></a>

Copy a random file from the source directory to the target directory and return the filename / relative path.

```php
$faker->file('docs', 'site', true);

// 'site/f6df6c74-2884-35c7-b802-6f96cf2ead01.md', 'site/423cfca4-709c-3942-8d66-34b08affd90b.md', 'site/c7a76943-e2cc-3c99-b75b-ac2df15cb3cf.md'

$faker->file('docs', 'site', false);

// 'c4cdee40-0eee-3172-9bca-bdafbb743c17.md', '88aef77e-040d-39a3-8f88-eca522f759ba.md', 'ecbee0e9-6fad-397b-88fb-d84704c7a71c.md'
```

## Image <a href="#image" id="image"></a>

### `imageUrl`[#](https://fakerphp.github.io/formatters/image/#imageurl) <a href="#imageurl" id="imageurl"></a>

Get a random image URL from [placeholder.com](https://placeholder.com/).

To provide a less verbose explanation of this function, we'll use a function definition here:

```php
function imageUrl(
    int $width = 640,
    int $height = 480,
    ?string $category = null, /* used as text on the image */
    bool $randomize = true,
    ?string $word = null,
    bool $gray = false,
    string $format = 'png'
): string;
```

Below, a few examples of possible parameter combinations:

```php
echo $faker->imageUrl(640, 480, 'animals', true);

// 'https://via.placeholder.com/640x480.png/004466?text=animals+omnis'

echo $faker->imageUrl(360, 360, 'animals', true, 'cats');

// 'https://via.placeholder.com/360x360.png/00bbcc?text=animals+cats+vero'

echo $faker->imageUrl(360, 360, 'animals', true, 'dogs', true);

// https://via.placeholder.com/360x360.png/CCCCCC?text=animals+dogs+veniam

echo $faker->imageUrl(360, 360, 'animals', true, 'dogs', true, 'jpg');

// https://via.placeholder.com/360x360.jpg/CCCCCC?text=animals+dogs+veniam
```

### `image`[#](https://fakerphp.github.io/formatters/image/#image_1) <a href="#image_1" id="image_1"></a>

Get a random `image` from [placeholder.com](https://placeholder.com/) and download it to a directory (`$dir`). The full path of the image is returned as a `string`.

All the parameters are the same as `imageUrl`. Except an extra first parameter, this defines where the image should be stored.

```php
function image(
    ?string $dir = null,
    int $width = 640,
    int $height = 480,
    ?string $category = null,
    bool $fullPath = true,
    bool $randomize = true,
    ?string $word = null,
    bool $gray = false,
    string $format = 'png'
)
```

Below, a few examples of possible parameter combinations:

```php
echo $faker->image(null, 640, 480);

// '/tmp/309fd63646f6d781848850277c14aef2.png'

echo $faker->image(null, 360, 360, 'animals', true);

// '/tmp/4d2666e5968e10350428e3ed64de9175.png'

echo $faker->image(null, 360, 360, 'animals', true, true, 'cats', true);

// '/tmp/9444227f06f0b024a14688ef3b31fe7a.png'

echo $faker->image(null, 360, 360, 'animals', true, true, 'cats', true, 'jpg');

// '/tmp/9444227f06f0b024a14688ef3b31fe7a.jpg'
```

## [UUID](https://fakerphp.github.io/formatters/uuid/) <a href="#uuid" id="uuid"></a>

### `uuid`[#](https://fakerphp.github.io/formatters/uuid/#uuid_1) <a href="#uuid_1" id="uuid_1"></a>

Generate a random UUID.

```php
echo $faker->uuid();

// 'bf91c434-dcf3-3a4c-b49a-12e0944ef1e2', '5b2c0654-de5e-3153-ac1f-751cac718e4e'
```

## [Barcode](https://fakerphp.github.io/formatters/barcode/) <a href="#barcode" id="barcode"></a>

## &#x20;<a href="#barcode" id="barcode"></a>

### `ean13`[#](https://fakerphp.github.io/formatters/barcode/#ean13) <a href="#ean13" id="ean13"></a>

Generate a random [EAN-13](https://en.wikipedia.org/wiki/International_Article_Number) barcode.

```php
echo $faker->ean13();

// '5803352818140', '4142935337533'
```

### `ean8`[#](https://fakerphp.github.io/formatters/barcode/#ean8) <a href="#ean8" id="ean8"></a>

Generate a random [EAN-8](https://en.wikipedia.org/wiki/International_Article_Number) barcode.

```php
echo $faker->ean8();

// '30272446', '00484527'
```

### `isbn10`[#](https://fakerphp.github.io/formatters/barcode/#isbn10) <a href="#isbn10" id="isbn10"></a>

Generate a random [ISBN-10](https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-10_check_digit_calculation) compliant `string`.

```php
echo $faker->isbn10();

// '4250151735', '8395066937'
```

### `isbn13`[#](https://fakerphp.github.io/formatters/barcode/#isbn13) <a href="#isbn13" id="isbn13"></a>

Generate a random [ISBN-13](https://en.wikipedia.org/wiki/International_Standard_Book_Number#ISBN-13_check_digit_calculation) compliant `string`.

```php
echo $faker->isbn13();

// '9786881116078', '9785625528412'
```

## [Miscellaneous](https://fakerphp.github.io/formatters/miscellaneous/) <a href="#miscellaneous" id="miscellaneous"></a>

### `boolean`[#](https://fakerphp.github.io/formatters/miscellaneous/#boolean) <a href="#boolean" id="boolean"></a>

Generate a random `bool`.

```php
echo $faker->boolean();

// true, true, false
```

### `md5`[#](https://fakerphp.github.io/formatters/miscellaneous/#md5) <a href="#md5" id="md5"></a>

Generate a random [MD5](https://en.wikipedia.org/wiki/MD5) hash `string`.

```php
echo $faker->md5();

// 'b1f447c2ee6029c7d2d8b3112ecfb160', '6d5d81469dfb247a15c9030d5aae38f1'
```

### `sha1`[#](https://fakerphp.github.io/formatters/miscellaneous/#sha1) <a href="#sha1" id="sha1"></a>

Generate a random [SHA-1](https://en.wikipedia.org/wiki/SHA-1) hash `string`.

```php
echo $faker->sha1();

// '20d1061c44ca4eef07e8d129c7000101b3e872af', '28cda1350140b3465ea8f65b933b1dad98ee5425'
```

### `sha256`[#](https://fakerphp.github.io/formatters/miscellaneous/#sha256) <a href="#sha256" id="sha256"></a>

Generate a random [SHA-256](https://en.wikipedia.org/wiki/SHA-2) hash `string`.

```php
echo $faker->sha256();

// 'bfa80759a5c40a8dd6694a3752bac231ae49c136396427815b0e33bd10974919'
```

### `locale`[#](https://fakerphp.github.io/formatters/miscellaneous/#locale) <a href="#locale" id="locale"></a>

Generate a random locale `string`.

```php
echo $faker->locale();

// 'ln_CD', 'te_IN', 'sh_BA'
```

### `countryCode`[#](https://fakerphp.github.io/formatters/miscellaneous/#countrycode) <a href="#countrycode" id="countrycode"></a>

Generate a random [two-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) `string`.

```php
echo $faker->countryCode();

// 'LK', 'UM', 'CZ'
```

### `countryISOAlpha3`[#](https://fakerphp.github.io/formatters/miscellaneous/#countryisoalpha3) <a href="#countryisoalpha3" id="countryisoalpha3"></a>

Generate a random [three-letter country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3) `string`.

```php
echo $faker->countryISOAlpha3();

// 'ZAF', 'UKR', 'MHL'
```

### `languageCode`[#](https://fakerphp.github.io/formatters/miscellaneous/#languagecode) <a href="#languagecode" id="languagecode"></a>

Generate a random [two-letter language code](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) `string`.

```php
echo $faker->languageCode();

// 'av', 'sc', 'as'
```

### `currencyCode`[#](https://fakerphp.github.io/formatters/miscellaneous/#currencycode) <a href="#currencycode" id="currencycode"></a>

Generate a random [currency code](https://en.wikipedia.org/wiki/ISO_4217) `string`.

```php
echo $faker->currencyCode();

// 'AED', 'SAR', 'KZT'
```

### `emoji`[#](https://fakerphp.github.io/formatters/miscellaneous/#emoji) <a href="#emoji" id="emoji"></a>

Generate a random emoji. K

```php
echo $faker->emoji();

// '😦', '😎', '😢'
```

## [Biased](https://fakerphp.github.io/formatters/biased/) <a href="#biased" id="biased"></a>

### `biasedNumberBetween`[#](https://fakerphp.github.io/formatters/biased/#biasednumberbetween) <a href="#biasednumberbetween" id="biasednumberbetween"></a>

Generate a random `integer`, with a bias using a given function.

```php
function biasedNumberBetween(
    int $min = 0, 
    int $max = 100, 
    string $function = 'sqrt'
): int;
```

Examples:

```php
echo $faker->biasedNumberBetween(0, 20);

// 14, 18, 12

echo $faker->biasedNumberBetween(0, 20, 'log');

// 9, 4, 12
```

## [HTML Lorem](https://fakerphp.github.io/formatters/html-lorem/) <a href="#html-lorem" id="html-lorem"></a>

### `randomHtml`[#](https://fakerphp.github.io/formatters/html-lorem/#randomhtml) <a href="#randomhtml" id="randomhtml"></a>

Generate a random HTML `string`, with a given maximum depth and width. By default, the depth and width are `4`.

Depth defines the maximum depth of the body.

Width defines the maximum of siblings each element can have.

```php
echo $faker->randomHtml();

// '<html><head><title>Laborum doloribus voluptatum vitae quia voluptatum ipsum veritatis.</title></head><body><form action="example.org" method="POST"><label for="username">sit</label><input type="text" id="username"><label for="password">amet</label><input type="password" id="password"></form><div class="et"><span>Numquam magnam.</span><p>Neque facere consequuntur autem quisquam.</p><ul><li>Veritatis sint.</li><li>Et ducimus.</li><li>Veniam accusamus cupiditate.</li><li>Eligendi eum et doloribus.</li><li>Voluptate ipsa dolores est.</li><li>Enim.</li><li>Dignissimos nostrum atque et excepturi.</li><li>Nisi veniam.</li><li>Voluptate nihil labore sapiente.</li><li>Ut.</li><li>Id suscipit.</li></ul><i>Qui tempora minima ad.</i></div></body></html>'
```

## Version <a href="#version" id="version"></a>

### `semver`[#](https://fakerphp.github.io/formatters/version/#semver) <a href="#semver" id="semver"></a>

Generate a random [semantic version v2.0.0](https://semver.org/spec/v2.0.0.html) string.

Optionally, the parameters `$preRelease` and `$build` can be set to `true` to randomly include pre-release and/or build parts into the version.

Examples:

```php
echo $faker->semver();

// 0.0.1, 1.0.0, 9.99.99

echo $faker->semver(true, true);

// 0.0.1-beta, 1.0.0-rc.1, 1.5.9+276e88b, 5.6.2-alpha.2+20180419085616
```

## [Locales](https://fakerphp.github.io/locales/en_HK/)

## English (Hong Kong SAR China)[#](https://fakerphp.github.io/locales/en_HK/#english-hong-kong-sar-china) <a href="#english-hong-kong-sar-china" id="english-hong-kong-sar-china"></a>

#### `Faker\Provider\en_HK\Address`[#](https://fakerphp.github.io/locales/en_HK/#fakerprovideren_hkaddress) <a href="#fakerprovideren_hkaddress" id="fakerprovideren_hkaddress"></a>

```php
// Generates a fake town name based on the words commonly found in Hong Kong
echo $faker->town(); // "Yuen Long"

// Generates a fake village name based on the words commonly found in Hong Kong
echo $faker->village(); // "O Tau"

// Generates a fake estate name based on the words commonly found in Hong Kong
echo $faker->estate(); // "Ching Lai Court"
```

#### `Faker\Provider\en_HK\Phone`[#](https://fakerphp.github.io/locales/en_HK/#fakerprovideren_hkphone) <a href="#fakerprovideren_hkphone" id="fakerprovideren_hkphone"></a>

```php
// Generates a Hong Kong mobile number (starting with 5, 6 or 9)
echo $faker->mobileNumber(); // "92150087"

// Generates a Hong Kong landline number (starting with 2 or 3)
echo $faker->landlineNumber(); // "32750132"

// Generates a Hong Kong fax number (starting with 7)
echo $faker->faxNumber(); // "71937729"
```

```
// Some code
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/learn-lavarel/tong-hop-nhung-truong-du-lieu-de-facker-seeder-migration-migrate-factory-full-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
