app\models\Interaction::toggleLike PHP Method

toggleLike() public static method

Like or unlike a song on behalf of a user.
public static toggleLike ( string $songId, User $user ) : Interaction
$songId string
$user User
return Interaction
    public static function toggleLike($songId, User $user)
    {
        $interaction = self::firstOrCreate(['song_id' => $songId, 'user_id' => $user->id]);
        if (!$interaction->exists) {
            $interaction->play_count = 0;
        }
        $interaction->liked = !$interaction->liked;
        $interaction->save();
        event(new SongLikeToggled($interaction));
        return $interaction;
    }

Usage Example

Example #1
0
 /**
  * Like or unlike a song as the currently authenticated user.
  *
  * @param Request $request
  *
  * @return \Illuminate\Http\JsonResponse
  */
 public function like(Request $request)
 {
     return response()->json(Interaction::toggleLike($request->input('song'), $request->user()));
 }