I encountered an issue during my development for a food delivery website made using the TALL stack (for public view pages) and FilamentPHP (for Admin Panel).
In the Home page, I was rendering popular categories through a CategoryCard
livewire component.
home.blade.php
:
...
@foreach ($popularCategories as $category)
<livewire:category-card :category="$category" :key="$category->id" />
@endforeach
...
Upon clicking a category card, I should be able to redirect to the /menu
route
which renders the Menu
blade view.
The Menu
livewire component uses tabs
(maryUI
Tab Component) as opposed to URL params, for switching between
categories, when one wants to view products of that particular category. The
selected category is controlled by a $selectedCategoryName
property defined in
the Menu
component.
Problem: #
When I click on a popular category card on the home page, it should take me to
the /menu
route as well as activate that particular category tab (so I can
instantly see the items of that category).
Solution: #
- Using
Flash
Messages:
- Adding the following method in
CategoryCard.php
:
public function redirectToMenu() { session()->flash('category', $this->category->name); $this->redirect('/menu'); }
- Attaching it to the blade view
category-card.blade.php
usingwire:click
:
<div wire:key="{{ $category->id }}" wire:click="redirectToMenu"> {{-- category card view logic --}} </div>
- Adding the following method in
- Accessing the flash data in the
Menu
component:- Add inside the
mount()
method:
if (session('category')) { $this->sessionFlashSelectedCategoryName = session('category'); }
- Set the
$selectedCategoryName
(controls the current tab) property:
@script <script> // Set the `selectedCategoryName` tab to the category name retrieved from the session value $wire.$set('selectedCategoryName', $wire.sessionFlashSelectedCategoryName); </script> @endscript
- Add inside the