Hello Devs,
In this tutorial, we are going to learn how to create search with pagination livewire laravel.
Follow this step by step guide given below:
Step 1 :
Install Laravel 7
composer create-project --prefer-dist laravel/laravel blog
Step 2 :
Seed Database
public function run()
{
factory(App\User::class,500)->create();
}
Step 3 :
Create Component
php artisan make:livewire search
app/Http/Livewire/Search.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithPagination;
use App\User;
class Search extends Component
{
use WithPagination;
public $searchTerm;
public function render()
{
$searchTerm = '%'.$this->searchTerm.'%';
return view('livewire.search',[
'users' => User::where('name','like', $searchTerm)->paginate(10)
]);
}
}
resources/views/livewire/search.blade.php
<div class="container">
<div class="row">
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Search" wire:model="searchTerm" />
<table class="table table-bordered" style="margin: 10px 0 10px 0;">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
@foreach($users as $user)
<tr>
<td>
{{ $user->name }}
</td>
<td>
{{ $user->email }}
</td>
</tr>
@endforeach
</table>
{{ $users->links() }}
</div>
</div>
</div>
Step 4 :
Create Route routes/web.php
Route::get('/search-box', function () {
return view('searchbox');
});
Step 5 :
Create View File resources/views/searchbox.blade.php
<!DOCTYPE html>
<html>
<head>
<title></title>
@livewireStyles
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div class="container mt-4">
<div class="row">
<div class="col-md-8 offset-2">
<div class="card">
<div class="card-header bg-success text-white ">
<strong>Search with Laravel Livewire - Nicesnippets.com</strong>
</div>
<div class="card-body">
@livewire('search')
</div>
</div>
</div>
</div>
</div>
</body>
<script src="{{ asset('js/app.js') }}"></script>
@livewireScripts
</html>
Run this command:
php artisan serve
Open this URL:
http://localhost:8000/search-box
I hope this example helps you.