Вот пример, который должен работать с вами.
<?php
// Get the post from the database
$post = \App\Post::find($request->id);
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
// Declare an empty variable that will determine if
// the post is being "liked" or "disliked"
$postAction = '';
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// The post has at least 1 like
$postAction = 'dislike';
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// The post has 0 likes
$postAction = 'like';
// Increment the likes by 1
$socialPost->increment('likes', 1);
}
// Determine if this was a new SocialPost record
if ($socialPost->wasRecentlyCreated)
{
// Override the post action as "New table"
$postAction = 'New table';
}
// Return the goods
return json_encode(['status' => true, 'msg' => $postAction]);
Объяснение
Вы можете определить, существует ли запись SocialPost, или создать новую - все в одной строке, используя firstOrCreate
, на который есть ссылка вдокументация здесь .Первый параметр массива принимает то, что вы ищете, а второй параметр массива принимает то, что должно быть создано, если первый параметр ничего не дал
// Find the SocialPost record if it exists,
// if it doesn't create a new one with no likes
$socialPost = SocialPost::firstOrCreate(
['user_id' => $request->user_id, 'post_id' => $post->id],
['user_id' => $request->user_id, 'post_id' => $post->id, 'likes' => 0, 'view' => 0, 'creator' => 1],
);
Тогда вы можете очистить добавление или вычитание лайков с помощьюиспользуя increment
или decrement
, указанные в документации здесь .
// Determine if the post has likes or not
if ($socialPost->likes > 0)
{
// Decrement the likes by 1
$socialPost->decrement('likes', 1);
}
else
{
// Increment the likes by 1
$socialPost->increment('likes', 1);
}