Laravel 9 Пример простого поиска с пагинацией

В этой статье мы рассмотрим, как использовать простой поиск с пагинацией в laravel 9. Перед началом работы вам необходимо установить laravel breeze start kit for ui.

Создайте проект Laravel

Выполните приведенную ниже команду в терминале, чтобы создать проект laravel.

composer create-project laravel/laravel laravel-search 
Войти в полноэкранный режим Выйдите из полноэкранного режима

Установите laravel Breeze.
Аутентификация в Laravel 9 с помощью Laravel Breeze

Создание фальшивых данных пользователя

Laravel provider users fake data вам нужно просто откомментировать seeder и запустить seeder.
database/seeders/DatabaseSeeder.php

<?php

namespace DatabaseSeeders;

use IlluminateDatabaseSeeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        AppModelsUser::factory(20)->create();

        // AppModelsUser::factory()->create([
        //     'name' => 'Test User',
        //     'email' => 'test@example.com',
        // ]);
    }
}
Вход в полноэкранный режим Выход из полноэкранного режима

Запустите seeder с миграцией.

php artisan migrate:fresh --seed
Войти в полноэкранный режим Выход из полноэкранного режима

Создание контроллера пользователя

Выполните приведенную ниже команду для создания контроллера пользователя.

php artisan make:controller UserController
Войти в полноэкранный режим Выйти из полноэкранного режима

Добавьте функциональность поиска с пагинацией.
app/Http/UserController.php

<?php

namespace AppHttpControllers;

use AppModelsUser;
use IlluminateHttpRequest;

class UserController extends Controller
{
    public function index(Request $request)
    {
        $users = User::where([
            ['name', '!=', Null],
            [function ($query) use ($request) {
                if (($s = $request->s)) {
                    $query->orWhere('name', 'LIKE', '%' . $s . '%')
                        ->orWhere('email', 'LIKE', '%' . $s . '%')
                        ->get();
                }
            }]
        ])->paginate(6);

        return view('users.index', compact('users'));
    }
}
Вход в полноэкранный режим Выход из полноэкранного режима

web.php

<?php

use AppHttpControllersUserController;
use IlluminateSupportFacadesRoute;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Route::get('users', [UserController::class,'index'])->name('users.search');
require __DIR__.'/auth.php';
Вход в полноэкранный режим Выход из полноэкранного режима

Создайте файл User Blade с формой поиска.

views/users/index.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="text-xl font-semibold leading-tight text-gray-800">
            {{ __('Users') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="mx-auto max-w-7xl sm:px-6 lg:px-8">
            <div class="overflow-hidden bg-white shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                    <div class="mt-1 mb-4">
                        <div class="relative max-w-xs">
                            <form action="{{ route('users.search') }}" method="GET">
                                <label for="search" class="sr-only">
                                    Search
                                </label>
                                <input type="text" name="s"
                                    class="block w-full p-3 pl-10 text-sm border-gray-200 rounded-md focus:border-blue-500 focus:ring-blue-500 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400"
                                    placeholder="Search..." />
                                <div class="absolute inset-y-0 left-0 flex items-center pl-4 pointer-events-none">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 text-gray-400" fill="none"
                                        viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                            d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                                    </svg>
                                </div>
                            </form>
                        </div>

                    </div>
                    <div class="relative overflow-x-auto shadow-md sm:rounded-lg">
                        <table class="w-full text-sm text-left text-gray-500 dark:text-gray-400">
                            <thead
                                class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
                                <tr>
                                    <th scope="col" class="px-6 py-3">
                                        #
                                    </th>
                                    <th scope="col" class="px-6 py-3">
                                        Name
                                    </th>
                                    <th scope="col" class="px-6 py-3">
                                        Email
                                    </th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($users as $user)
                                <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
                                    <th scope="row"
                                        class="px-6 py-4 font-medium text-gray-900 dark:text-white whitespace-nowrap">
                                        {{$user->id}}
                                    </th>
                                    <td class="px-6 py-4">
                                        {{$user->name}}

                                    </td>
                                    <td class="px-6 py-4">
                                        {{$user->email}}

                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                        {{ $users->links() }}
                    </div>

                </div>
            </div>
        </div>
    </div>
</x-app-layout>
Войти в полноэкранный режим Выйти из полноэкранного режима

Оцените статью
devanswers.ru
Добавить комментарий