To achieve the desired functionality of searching the InventoryInStore table by Item name or Category name using Laravel and Livewire, you can follow these steps:
-
Define Relationships in Models:
First, ensure that the relationships between your models are properly defined. This will allow you to easily query related data.
// Item.php public function inventoryItems() { return $this->hasMany(InventoryItem::class); } // Category.php public function inventoryItems() { return $this->hasMany(InventoryItem::class); } // InventoryItem.php public function item() { return $this->belongsTo(Item::class); } public function category() { return $this->belongsTo(Category::class); } public function inventoryInStore() { return $this->hasMany(InventoryInStore::class); } // InventoryInStore.php public function inventoryItem() { return $this->belongsTo(InventoryItem::class); } -
Create a Livewire Component:
Create a Livewire component that will handle the search functionality.
php artisan make:livewire InventorySearch -
Implement the Search Logic in the Livewire Component:
In the
InventorySearchcomponent, implement the logic to search byItemname orCategoryname.// InventorySearch.php namespace App\Http\Livewire; use Livewire\Component; use App\Models\InventoryInStore; class InventorySearch extends Component { public $searchTerm; public function render() { $searchTerm = '%' . $this->searchTerm . '%'; $inventoryInStores = InventoryInStore::whereHas('inventoryItem.item', function ($query) use ($searchTerm) { $query->where('name', 'like', $searchTerm); }) ->orWhereHas('inventoryItem.category', function ($query) use ($searchTerm) { $query->where('name', 'like', $searchTerm); }) ->with(['inventoryItem.item', 'inventoryItem.category']) ->get(); return view('livewire.inventory-search', [ 'inventoryInStores' => $inventoryInStores, ]); } } -
Create the Blade View:
Create a Blade view for the Livewire component to display the search results.
<!-- resources/views/livewire/inventory-search.blade.php --> <div> <input type="text" wire:model="searchTerm" placeholder="Search by Item or Category Name"> <table> <thead> <tr> <th>Item Name</th> <th>Category Name</th> <th>Quantity</th> </tr> </thead> <tbody> @foreach($inventoryInStores as $inventoryInStore) <tr> <td>{{ $inventoryInStore->inventoryItem->item->name }}</td> <td>{{ $inventoryInStore->inventoryItem->category->name }}</td> <td>{{ $inventoryInStore->qty }}</td> </tr> @endforeach </tbody> </table> </div> -
Include the Livewire Component in Your View:
Finally, include the Livewire component in your main view where you want the search functionality to appear.
@livewire('inventory-search')
This setup will allow you to search the InventoryInStore table by Item name or Category name and display the results dynamically using Livewire. Make sure to adjust the relationships and field names according to your actual database schema if they differ.