$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
<?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
<?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');
}
}
<?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');
}
}
<?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');
}
}
<?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');
}
}
<?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');
}
}
<?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');
}
}
<?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();
}
}
<?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);
}
}
<?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);
}
}
<?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'];
}
<?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 [];
}
}
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.
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:
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'));
}
}
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:
<?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() !!}.
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:
Okay we are finally here just add the following CSS style in the head of the home.blade.php file.
<?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'];
}
<?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');
}
}
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.
echo $faker->randomNumber(5,false);// 123, 43, 19238, 5, or 1203echo $faker->randomNumber(5,true);// 12643, 42931, or 32919
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.
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%.
echo $faker->sentence();// 'Sit vitae voluptas sint non voluptates.'echo $faker->sentence(3);// 'Laboriosam non voluptas.'
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.
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.']
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%.
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.'
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.
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.
Generate a random string of text. The first parameter represents the maximum number of characters the text should contain (by default, 200).
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.
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).
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.
echo $faker->unixTime();// 1605544623, 1025544612echo $faker->unixTime(newDateTime('+3 weeks'));// unix timestamp between 0 and the date 3 weeks from now.
Generate a DateTime between two dates. By default, -30 years and now are used.
An optional third parameter can be supplied, with the timezone.
echo $faker->dateTimeBetween();// a date between -30 years ago, and nowecho $faker->dateTimeBetween('-1 week','+1 week');// a date between -1 week ago, and 1 week from now
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.
echo $faker->dateTimeInInterval();// a date between -30 years ago, and -30 years + 5 daysecho $faker->dateTimeInInterval('-1 week','+3 days');// a date between -1 week ago, and -1 week + 3 days
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.
echo $faker->dateTimeThisCentury();// a date somewhere in this centuryecho $faker->dateTimeThisCentury('+8 years');// a date somewhere in this century, with an upper bound of +8 years
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.
echo $faker->dateTimeThisDecade();// a date somewhere in this decadeecho $faker->dateTimeThisDecade('+2 years');// a date somewhere in this decade, with an upper bound of +2 years
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.
echo $faker->dateTimeThisYear();// a date somewhere in this yearecho $faker->dateTimeThisYear('+2 months');// a date somewhere in this year, with an upper bound of +2 months
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.
echo $faker->dateTimeThisMonth();// a date somewhere in this monthecho $faker->dateTimeThisMonth('+12 days');// a date somewhere in this month, with an upper bound of +12 days
Generate a user agent that belongs to Apple Safari.
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'
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.
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.
echo $faker->creditCardExpirationDate();// DateTime: between now and +36 monthsecho $faker->creditCardExpirationDate(false);// DateTime: between -36 months and +36 months
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.
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.
To provide a less verbose explanation of this function, we'll use a function definition here:
functionimageUrl(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:
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.
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>'
// Generates a fake town name based on the words commonly found in Hong Kongecho $faker->town(); // "Yuen Long"// Generates a fake village name based on the words commonly found in Hong Kongecho $faker->village(); // "O Tau"// Generates a fake estate name based on the words commonly found in Hong Kongecho $faker->estate(); // "Ching Lai Court"
// 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"