ブートストラップ5を使用したLaravel 8のページ例


もともとhttps://codeanddeploy.com訪問し、サンプルコードをダウンロードしてください
このポストでは、ブートストラップ5を使用してLaLaVel 8のページ化を実装する方法の例を共有します.あなたが巨大なデータによるテーブルを持っていて、ページによってそれを表示したいならば、ラーラーベルの上でページ化をすることは必要です.
https://codeanddeploy.com/blog/laravel/laravel-8-pagination-example-using-bootstrap-5

ステップ1:ラーラベルインストール


Laravelのページ設定チュートリアルから始めるには.ローカルにLaravel 8をインストールしていない場合は、以下のコマンドを実行します.
composer create-project --prefer-dist laravel/laravel crud

ステップ2:データベース構成


あなたのLaravelプロジェクトが新鮮な場合は、データベースの資格情報を更新する必要があります.ジャストオープン.Lavavel 8プロジェクトのEnvファイル..env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name_here
DB_USERNAME=your_database_username_here
DB_PASSWORD=your_database_password_here

ステップ3 :移行設定


この例では、ユーザーのテーブルを使用しています.下記の移行例を参照してください.
<?php

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

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->string('email')->unique();
            $table->string('username')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}
次のコマンドを実行します.
php artisan migrate

ステップ4:モデルセットアップ


以下はLaravelのページネーションのために使用しているユーザーモデルのコード例です.
<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name',
        'email',
        'username',
        'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * Always encrypt password when it is updated.
     *
     * @param $value
     * @return string
     */
    public function setPasswordAttribute($value)
    {
        $this->attributes['password'] = bcrypt($value);
    }
}

ステップ5 : fakerを使って偽データを生成する


ラーラベルパッケージ を使用して、ユーザーのテーブルに偽データを生成します.
データベース\factory\userfactoryクラスでは、fakerを変更して実装します.
<?php

namespace Database\Factories;

use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class UserFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = User::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name(),
            'email' => $this->faker->unique()->safeEmail(),
            'username' => $this->faker->unique()->userName,
            'email_verified_at' => now(),
            'password' => 'test', // password
            'remember_token' => Str::random(10),
        ];
    }

    /**
     * Indicate that the model's email address should be unverified.
     *
     * @return \Illuminate\Database\Eloquent\Factories\Factory
     */
    public function unverified()
    {
        return $this->state(function (array $attributes) {
            return [
                'email_verified_at' => null,
            ];
        });
    }
}
次にデータベースを作成します.
\App\Models\User::factory(100)->create();
以下は完全なコードです.
<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        \App\Models\User::factory(100)->create();
    }
}
次のコマンドを実行します.
php artisan db:seed
そしてそれはあなたのユーザーのテーブルに100偽データを生成します.

フェーカー ステップ6 : LaravelのPageGationの例のためのコントローラとルートの作成


以下のコマンドを実行して、コントローラ
php artisan make:controller UsersController
次に、以下のコードをユーザコントローラファイルに置きます.
<?php

namespace App\Http\Controllers;

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

class UsersController extends Controller
{
    /**
     * Display all users
     * 
     * @return \Illuminate\Http\Response
     */
    public function index() 
    {
        $users = User::latest()->paginate(10);

        return view('users.index', compact('users'));
    }
}
上記のように、各ページに10個の結果が付いたLate ()メソッドの後にPageInite ()を呼び出します.結果をページで表示できるようになります.Laravel Paginationの詳細についてはこちらをご覧ください.
次に、ルートを作成します.
Route::get('/users', 'App\Http\Controllers\UsersController@index')->name('users.index');

ステップ7:ラーラベルのページのためのブレードビューを追加


あなたのリソース/ビュー/作成ユーザーフォルダにインデックスを作成します.ブレード.PHP
これは次のようになります.ブレード.PHP
<!DOCTYPE html>
    <html>

    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Laravel 8 Pagination Demo - codeanddeploy.com</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    </head>

    <body>
        <div class="container mt-5">
            <table class="table table-striped">
                <thead>
                <tr>
                    <th scope="col" width="1%">#</th>
                    <th scope="col" width="15%">Name</th>
                    <th scope="col">Email</th>
                    <th scope="col" width="10%">Username</th>
                </tr>
                </thead>
                <tbody>
                    @foreach($users as $user)
                        <tr>
                            <th scope="row">{{ $user->id }}</th>
                            <td>{{ $user->name }}</td>
                            <td>{{ $user->email }}</td>
                            <td>{{ $user->username }}</td>
                        </tr>
                    @endforeach
                </tbody>
            </table>

            <div class="d-flex">
                {!! $users->links() !!}
            </div>
        </div>
    </body>
</html>
上記のように、{ !!$ user -> links () !!}を呼び出します.Laravel 8のページ付けがビューに表示されるように機能します.

追加:


アプリケーション\プロバイダー\AppServiceProviderクラスでは、bootstrapパラメータをサポートするために、boot ()関数の中に以下のコードを追加する必要があります.
Paginator::useBootstrap();
コンプリートコード
<?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();
    }
}
今、あなたはそれが助けることを望むlaravel 8ページ化を実装する方法の基本的な例を持っています.
私はこのチュートリアルを助けることを望む.あなたがこのコードをダウンロードしたいならば、親切に をここで訪問してください.
ハッピーコーディング