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

https://fakerphp.github.io or https://github.com/fzaninotto/Faker

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

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

C:\xampp82\htdocs\testvn\database\migrations\2023_04_17_130047_create_posts_table.php

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

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

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

C:\xampp82\htdocs\testcom\database\migrations\2023_04_04_023335_create_roles_table.php

Một cách sử dụng class tác riêng ra kết hợp database\seeders\DatabaseSeeder.php

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

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

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

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

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

C:\xampp\htdocs\datvietcoconut\database\migrations\2022_12_09_185509_create_employees_table.php

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

Length firstName 😒

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

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

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

Factories

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

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

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

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

Migrations

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_11_01_164128_create_comments_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_11_01_115835_create_article_user_pivot_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_11_01_110547_create_article_tag_pivot_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_11_01_105716_create_tags_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_11_01_074539_create_articles_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_10_31_180730_create_followers_pivot_table.php

C:\xampp\htdocs\laravel-realworld-example-app\database\migrations\2021_10_31_000000_create_users_table.php

Seeders

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

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

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

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

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

Laravel 8 pagination Example with Bootstrap 4

June 24, 2021LaravelHome » Laravel » Laravel 8 pagination Example with Bootstrap 4

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.

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:

Step 3: Create Article model and migration

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

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.

Now we need to migrate the table we created.

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:

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:

Step 6: Create Controller and Route

Run the following command to create ArticleController.

Place the following code in the ArticleController.

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

Step 7: Create View

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

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.

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:

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.

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:

So the final result will look like this:

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:

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

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

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

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

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

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

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

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

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

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

Numbers and Strings#

randomDigit#

Generates a random integer from 0 until 9.

randomDigitNot#

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

randomDigitNotNull#

Generates a random integer from 1 until 9.

randomNumber#

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.

randomFloat#

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.

numberBetween#

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

randomLetter#

Generates a random character from the alphabet.

randomElements#

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

randomElement#

Returns a random element from the given array.

randomKey#

Returns a random key from the given array.

shuffle#

Returns a shuffled version of either an array or string.

numerify#

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

lexify#

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

bothify#

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.

asciify#

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

regexify#

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

word#

Generate a string containing random single word.

words#

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.

sentence#

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%.

sentences#

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.

paragraph#

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%.

paragraphs#

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.

text#

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

Date and Time#

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#

Generate an 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.

dateTime#

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.

dateTimeAD#

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.

iso8601#

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

date#

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.

time#

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.

dateTimeBetween#

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

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

dateTimeInInterval#

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.

dateTimeThisCentury#

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.

dateTimeThisDecade#

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.

dateTimeThisYear#

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.

dateTimeThisMonth#

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.

amPm#

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.

dayOfMonth#

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.

dayOfWeek#

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.

month#

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.

monthName#

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.

year#

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.

century#

Generate a random century name.

timezone#

Generate a random timezone name.

Internet#

email#

Generate an email address.

safeEmail#

Generate a safe email address.

freeEmail#

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

companyEmail#

Generate a company email.

freeEmailDomain#

Generate a free email domain name.

safeEmailDomain#

Generate a safe email domain.

userName#

Generate a username.

password#

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.

domainName#

Generate a domain name.

domainWord#

Generate a domain word.

tld#

Generate a tld (top-level domain).

url#

Generate a URL.

slug#

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.

ipv4#

Generate an IPv4 address.

localIpv4#

Generate an IPv4 address, inside a local subnet.

ipv6#

Generate an IPv6 address.

macAddress#

Generate a random MAC address.

userAgent#

Generate a user agent.

chrome#

Generate a user agent that belongs to Google Chrome.

firefox#

Generate a user agent that belongs to Mozilla Firefox.

safari#

Generate a user agent that belongs to Apple Safari.

opera#

Generate a user agent that belongs to Opera.

internetExplorer#

Generate a user agent that belongs to Internet Explorer.

msedge#

Generate a user agent that belongs to Microsoft Ege.

creditCardType#

Generate a credit card type.

creditCardNumber#

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.

creditCardExpirationDate#

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.

creditCardExpirationDateString#

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.

creditCardDetails#

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.

iban#

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.

swiftBicNumber#

Generate a random SWIFT/BIC number string.

hexColor#

Generate a random hex color.

safeHexColor#

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

rgbColorAsArray#

Generate a random RGB color, as an array.

rgbColor#

Generate a comma-separated RGB color string.

rgbCssColor#

Generate a CSS-friendly RGB color string.

rgbaCssColor#

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

safeColorName#

Generate a CSS-friendly color name.

colorName#

Generate a CSS-friendly color name.

hslColor#

Generate a random HSL color string.

hslColorAsArray#

Generate a random HSL color, as an array.

mimeType#

Generate a random MIME-type string.

fileExtension#

Generate a random file extension type string.

file#

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

Image

imageUrl#

Get a random image URL from placeholder.com.

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

Below, a few examples of possible parameter combinations:

image#

Get a random image from 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.

Below, a few examples of possible parameter combinations:

uuid#

Generate a random UUID.

ean13#

Generate a random EAN-13 barcode.

ean8#

Generate a random EAN-8 barcode.

isbn10#

Generate a random ISBN-10 compliant string.

isbn13#

Generate a random ISBN-13 compliant string.

boolean#

Generate a random bool.

md5#

Generate a random MD5 hash string.

sha1#

Generate a random SHA-1 hash string.

sha256#

Generate a random SHA-256 hash string.

locale#

Generate a random locale string.

countryCode#

Generate a random two-letter country code string.

countryISOAlpha3#

Generate a random three-letter country code string.

languageCode#

Generate a random two-letter language code string.

currencyCode#

Generate a random currency code string.

emoji#

Generate a random emoji. K

biasedNumberBetween#

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

Examples:

randomHtml#

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.

Version

semver#

Generate a random semantic version v2.0.0 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:

English (Hong Kong SAR China)#

Faker\Provider\en_HK\Address#

Faker\Provider\en_HK\Phone#

Last updated

Was this helpful?