I made a like/favorite button (heart) and want it to go blue when you clicked it.
This works fine except when you click another heart, the first heart that was bluen turns white again and only the last clicked heart turns blue.
Every time you click on another hearth only the last clicked heart turns blue!!
The rest works fine but i dont know why this happens, anybody?
class Products extends Component
{
public $orderBy;
public $vacid;
public function mount()
{
$this->orderBy = "Sorteer: Nieuwste Vacatures";
if(Auth::id()) {
$user = Auth::user();
$fav = Favoriet::where('user_id','=',$user->id)->get();
foreach($fav as $fav){
$this->vacid = $fav->vacature_id;
}
}
}
@if($vac->id == $vacid)
<a class="bi bi-heart-fill fa-lg m-2" href="{{url('favorieten',$vac->id)}}"
data-tooltip="tooltip" data-placement="top" title="Voeg toe aan favorieten">
</a>
@else
<a class="bi bi-heart fa-lg m-2" href="{{url('favorieten',$vac->id)}}"
data-tooltip="tooltip" data-placement="top" title="Voeg toe aan favorieten">
</a>
@endif
<div class="border"></div>
@endforeach
</div>
>Solution :
This ensures that all liked items are stored in the $this->vacids array, and you can then check if the current $vac->id is in that array. This way, each liked item will retain its blue color after being clicked.
class Products extends Component
{
public $orderBy;
public $vacids = []; // Change to array
public function mount()
{
$this->orderBy = "Sorteer: Nieuwste Vacatures";
if (Auth::id()) {
$user = Auth::user();
$fav = Favoriet::where('user_id', '=', $user->id)->get();
foreach ($fav as $fav) {
$this->vacids[] = $fav->vacature_id; // Store all $vac->id values in an array
}
}
}
}
// ...
@if (in_array($vac->id, $this->vacids))
<a class="bi bi-heart-fill fa-lg m-2" href="{{url('favorieten',$vac->id)}}"
data-tooltip="tooltip" data-placement="top" title="Voeg toe aan favorieten">
</a>
@else
<a class="bi bi-heart fa-lg m-2" href="{{url('favorieten',$vac->id)}}"
data-tooltip="tooltip" data-placement="top" title="Voeg toe aan favorieten">
</a>
@endif