Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

dmytroshved's avatar

Optimization in Like/Dislike buttons. Livewire 3

Hello

I have logic for like/dislike button in two separate livewire components

The problem is I want it to optimize db requests

At this moment after clicking like/dislike buttons I am getting 5-6 db queries:

select * from `sessions` where `id` = '...' limit 1
select * from `recipes` where `recipes`.`id` = 1 limit 1
select * from `users` where `id` = 1 limit 1

select exists(select * from `likes` where `likes`.`user_id` = 1 and `likes`.`user_id` is not null and (`recipe_id` = 1 and `liked` = 1)) as `exists`

select * from `likes` where `likes`.`recipe_id` = 1 and `likes`.`recipe_id` is not null and (`user_id` = 1) limit 1

insert into `likes` (`user_id`, `liked`, `recipe_id`, `updated_at`, `created_at`) values (1, 1, 1, '2025-05-09 05:28:38', '2025-05-09 05:28:38')

Code:


LikeButton.php:

DislikeButton.php:

As you see there is some duplication at the moment when we're getting auth user.

Would be grateful for some help


EDIT 01

Likable.php (trait for model Recipe.php)

1 like
3 replies
Snapey's avatar

one possible optimization is to come at it the other way. Instead of thinking has this user liked this recipe, think has the recipe been liked by this user?

If you create a relationship for likedByUser on the recipe model, you can load the likedBy with the recipe, and then just check that loaded relationship in your button component rather than requerying the database.

1 like

Please or to participate in this conversation.