我在我的Article模型中使用了一些函式,它們為特定文章的 cookie 添加喜歡并記錄時間
public static function hasLikedToday($articleId, string $type)
{
$articleLikesJson = \Cookie::get('article_likes', '{}');
$articleLikes = json_decode($articleLikesJson, true);
// Check if there are any likes for this article
if (! array_key_exists($articleId, $articleLikes)) {
return false;
}
// Check if there are any likes with the given type
if (! array_key_exists($type, $articleLikes[$articleId])) {
return false;
}
$likeDatetime = Carbon::createFromFormat('Y-m-d H:i:s', $articleLikes[$articleId][$type]);
return ! $likeDatetime->addDay()->lt(now());
}
public static function setLikeCookie($articleId, string $type)
{
// Initialize the cookie default
$articleLikesJson = \Cookie::get('article_likes', '[]');
$articleLikes = json_decode($articleLikesJson, true);
// Update the selected articles type
$articleLikes[$articleId][$type] = today()->format('Y-m-d H:i:s');
$articleLikesJson = json_encode($articleLikes);
return cookie()->forever('article_likes', $articleLikesJson);
}
該php.blade頁面本身有按鈕
<a href="/article/{{ $article->id }}/like?type=heart" class="btn btn-primary">Like Heart</a>
<a href="/article/{{ $article->id }}/like?type=finger" hljs-string">">Like Finger</a>
以下是路線 web.php
Route::get('/article', function () {
$articleLikesJson = \Cookie::get('article_likes', '{}');
return view('article')->with([
'articleLikesJson' => $articleLikesJson,
]);
});
Route::get('article/{id}/like', 'App\Http\Controllers\ArticleController@postLike');
而postLike()函式本身在controller
public function postLike($id) {
$article = Article::find($id);
$like = request('like');
if ($article->hasLikedToday($article->id, $like)) {
return response()
->json([
'message' => 'You have already liked the Article #'.$article->id.' with '.$like.'.',
]);
}
$cookie = $article->setLikeCookie($article->id, $like);
$article->increment('like_{$like}');
return response()
->json([
'message' => 'Liked the Article #'.$article->id.' with '.$like.'.',
'cookie_json' => $cookie->getValue(),
])
->withCookie($cookie);
}
一般來說,有什么問題,我有2種型別的like可以在 中看到php.blade,問題是將like型別的選擇傳遞給postLike()函式,如果在我的函式中而不是$like我寫'heart',那么一切都會作業,但我需要確定我們選擇哪種型別(心臟或手指),告訴我如何做到這一點?
uj5u.com熱心網友回復:
你可以使用 Laravel 的 Request 物件。
https://laravel.com/docs/8.x/requests#input
像這樣:
use Illuminate\Http\Request;
public function postLike($id, Request $request)
{
$type = $request->input('type');
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/344428.html
