Tengo un método para agregar Me gusta a una página.
hoja.php
<a href="/article/{{ $article->id }}?type=heart" class="comments-sub-header__item like-button"> <div class="comments-sub-header__item-icon-count"> {{ $article->like_heart }} </div> <a href="/article/{{ $article->id }}?type=finger" class="comments-sub-header__item like-button"> <div class="comments-sub-header__item-icon-count"> {{ $article->like_finger }} </div>Agregar un Me gusta al hacer clic
js
$(function() { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), }, }); $('.like-button').on('click', function(event) { event.preventDefault(); let href = $(this).attr('href'); $.ajax({ url: href, type: 'POST', success: function() { window.location.reload(); }, }); }); }); A continuación, hice una clase active con estilos, y cuando hago clic en me gusta en la clase class="comments-sub-header__item like-button" esta clase debería agregarse active
Pero hay una cosa más, mis me gusta se almacenan en cookies, y 24 horas después de hacer clic podemos poner un nuevo me gusta, es decir, la clase active también debe desactivarse después de 24 horas
Así lo implementé agregando un me gusta a las cookies
Route::post('article/{id}', 'App\Http\Controllers\ArticleController@postLike'); public function postLike($id, Request $request) { $article = Article::find($id); if(!$article){ return abort(404); } $type = $request->input('type'); if ($article->hasLikedToday($type)) { return response() ->json([ 'message' => 'You have already liked the Article '.$article->id.' with '.$type.'.', ]); } $cookie = $article->setLikeCookie($type); $article->increment("like_{$type}"); return response() ->json([ 'message' => 'Liked the Article '.$article->id.' with '.$type.'.', 'cookie_json' => $cookie->getValue(), ]) ->withCookie($cookie); } public function hasLikedToday(string $type) { $articleLikesJson = Cookie::get('article_likes', '{}'); $articleLikes = json_decode($articleLikesJson, true); if (!array_key_exists($this->id, $articleLikes)) { return false; } if (!array_key_exists($type, $articleLikes[$this->id])) { return false; } $likeDatetime = Carbon::createFromFormat('Ymd H:i:s', $articleLikes[$this->id][$type]); return ! $likeDatetime->addDay()->lt(now()); } public function setLikeCookie(string $type) { $articleLikesJson = Cookie::get('article_likes', '[]'); $articleLikes = json_decode($articleLikesJson, true); $articleLikes[$this->id][$type] = now()->format('Ymd H:i:s'); $articleLikesJson = json_encode($articleLikes); return cookie()->forever('article_likes', $articleLikesJson); } Según tengo entendido, todo esto debería hacerse en js , pero todavía no lo entiendo muy bien, así que pido una pista.
Simplemente comparta una variable en la vista donde muestra los botones "me gusta" en algún lugar de su controlador:
// Your controller public function show(Request $request, $postId) { $post = Post::find($postId); $hasLikedToday = $post->hasLikedToday('heart'); return view('your.view.file', [ 'article' => $article, 'hasLikedToday' => $hasLikedToday, // share this variable to check if you've liked today ]); } Después de enviar la variable hasLikedToday a su hoja donde se definen los botones Me gusta, simplemente verifique si la variable es true , si es así, muestre la clase activa. Ahora, cada vez que actualice esa página, verificará si se debe mostrar la clase activa, no es necesario que JavaScript lo haga.
<a href="/article/{{ $article->id }}?type=heart" class=" ... {{ $hasLikedToday ? 'active' : '' }}"> <div class="comments-sub-header__item-icon-count"> {{ $article->like_heart }} </div>