In this lesson, let's add a search by name and category above the table. And here you will see where Livewire shines. After changing any of the inputs, the table will be refreshed without any JS code line.
Add Search Inputs
First, we need to add inputs above the table. But before that, let's quickly add categories to the products.
database/migrations/xxxx_create_categories_table.php:
Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamps();});
database/migrations/xxxx_add_category_id_to_products_table.php:
Schema::table('products', function (Blueprint $table) { $table->foreignId('category_id')->after('id');});
app/Models/Product.php:
use Illuminate\Database\Eloquent\Relations\BelongsTo; class Product extends Model{ // ... public function category(): BelongsTo { return $this->belongsTo(Category::class); }}
database/factories/CategoryFactory.php:
class CategoryFactory extends Factory{ public function definition(): array { return [ 'name' => $this->faker->words(asText: true), ]; }}
database/factories/ProductFactory.php:
use App\Models\Category; class ProductFactory extends Factory{ public function definition(): array { $categories = collect(Category::pluck('id')); return [ 'category_id' => $categories->random(), 'name' => $this->faker->name(), 'description' => $this->faker->text(50), ]; }}
database/seeders/DatabaseSeeder.php:
class DatabaseSeeder extends Seeder{ public function run(): void { Category::factory(10)->create(); Product::factory(50)->create(); }}
We must eager load categories in the Products
Livewire component to avoid the N+1 issue. Also, I will refactor it into a separate variable for...