PHP code example of andydefer / laravel-likes

1. Go to this page and download the library: Download andydefer/laravel-likes library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

andydefer / laravel-likes example snippets




return [
    /*
    |--------------------------------------------------------------------------
    | Enum Casts
    |--------------------------------------------------------------------------
    |
    | Define enum casts for specific tables and columns.
    | Each entry maps a table name and column to an enum class.
    |
    | The enum class must implement EnumerableInterface.
    |
    */
    'enum_casts' => [
        'likes' => [
            'type' => App\Enums\CustomLikeType::class, // Votre enum personnalisé
        ],
    ],
];



declare(strict_types=1);

namespace App\Enums;

use AndyDefer\Repository\Contracts\EnumerableInterface;

enum CustomLikeType: string implements EnumerableInterface  // ⚠️ Interface obligatoire
{
    case LIKE = 'like';
    case LOVE = 'love';
    case HAHA = 'haha';
    case WOW = 'wow';
    case SAD = 'sad';
    case ANGRY = 'angry';
    // Ajoutez autant de cas que vous voulez !

    /**
     * Obligatoire - Retourne la valeur brute de l'énumération
     */
    public function getValue(): string
    {
        return $this->value;
    }

    /**
     * Optionnel - Méthode utilitaire pour l'affichage
     */
    public function getEmoji(): string
    {
        return match ($this) {
            self::LIKE => '👍',
            self::LOVE => '❤️',
            self::HAHA => '😂',
            self::WOW => '😮',
            self::SAD => '😢',
            self::ANGRY => '😡',
        };
    }

    /**
     * Optionnel - Méthode utilitaire pour l'affichage
     */
    public function getLabel(): string
    {
        return match ($this) {
            self::LIKE => 'J\'aime',
            self::LOVE => 'J\'adore',
            self::HAHA => 'Haha',
            self::WOW => 'Wow',
            self::SAD => 'Triste',
            self::ANGRY => 'En colère',
        };
    }
}

// config/repository.php
'enum_casts' => [
    'likes' => [
        'type' => App\Enums\CustomLikeType::class,
    ],
],

use App\Enums\CustomLikeType;

// Toggle avec votre enum
$liked = $likeService->toggle($user, $post, CustomLikeType::LIKE);

// Compter par type
$count = $likeService->countLikesByType($post, CustomLikeType::LOVE);

// Récupérer les likeurs par type
$likers = $likeService->getLikersByType($post, CustomLikeType::HAHA);

use AndyDefer\LaravelLikes\Services\LikeService;
use App\Enums\CustomLikeType;

class PostController extends Controller
{
    public function react(LikeService $likeService, Post $post)
    {
        $user = auth()->user();

        // Toggle une réaction
        $reacted = $likeService->toggle($user, $post, CustomLikeType::LIKE);

        return response()->json([
            'reacted' => $reacted,
            'type' => $reacted ? CustomLikeType::LIKE->getValue() : null,
            'emoji' => $reacted ? CustomLikeType::LIKE->getEmoji() : null,
        ]);
    }
}

// Ajoute un like - Lève une exception si déjà liké
$likeService->like($user, $post);

// Supprime un like - Lève une exception si non liké
$likeService->unlike($user, $post);

// Vérifier si l'utilisateur a réagi
$hasLiked = $likeService->hasLiked($user, $post);

// Compter toutes les réactions d'un objet
$total = $likeService->countLikes($post);

// Compter par type
$likes = $likeService->countLikesByType($post, CustomLikeType::LIKE);
$loves = $likeService->countLikesByType($post, CustomLikeType::LOVE);

// Récupérer tous les likeurs d'un objet
$likers = $likeService->getLikers($post);

// Récupérer les likeurs par type
$likersByType = $likeService->getLikersByType($post, CustomLikeType::LOVE);

// Récupérer toutes les réactions d'un utilisateur
$userLikes = $likeService->getLikerLikes($user);

// Récupérer les réactions d'un utilisateur par type
$userLoves = $likeService->getLikerLikesByType($user, CustomLikeType::LOVE);

use AndyDefer\PhpVo\ValueObjects\DateTimeVO;

$date = DateTimeVO::from('2024-01-01 00:00:00');

// Récupérer toutes les réactions mises à jour après une date
$recentLikes = $likeService->getLikesUpdatedAfter($date);

// Récupérer les réactions d'un utilisateur après une date
$userRecentLikes = $likeService->getLikerLikesUpdatedAfter($user, $date);

// Récupérer les réactions d'un objet après une date
$postRecentLikes = $likeService->getLikesForLikeableUpdatedAfter($post, $date);

$like = Like::find(1);

// ✅ Accès via les accesseurs Eloquent (propriétés directement)
$createdAt = $like->created_at;       // Carbon
$updatedAt = $like->updated_at;       // Carbon
$deletedAt = $like->deleted_at;       // Carbon
$metadata = $like->metadata;          // StrictDataObject|null
$type = $like->type;                  // EnumerableInterface (votre enum)

// ✅ Relations
$liker = $like->liker;          // Auteur (User, Admin, etc.)
$likeable = $like->likeable;    // Objet liké (Post, Article, etc.)

use AndyDefer\LaravelLikes\Services\LikeService;
use App\Enums\CustomLikeType;

class PostController extends Controller
{
    public function __construct(
        private readonly LikeService $likeService
    ) {}

    public function react(Request $request, Post $post)
    {
        $user = $request->user();
        $type = CustomLikeType::tryFrom($request->input('type', 'like'));

        if (!$type) {
            return response()->json(['error' => 'Type de réaction invalide'], 400);
        }

        $reacted = $this->likeService->toggle($user, $post, $type);

        return response()->json([
            'reacted' => $reacted,
            'type' => $reacted ? $type->getValue() : null,
            'emoji' => $reacted ? $type->getEmoji() : null,
            'label' => $reacted ? $type->getLabel() : null,
            'stats' => $this->getReactionStats($post),
        ]);
    }

    private function getReactionStats(Post $post): array
    {
        $stats = [];
        
        foreach (CustomLikeType::cases() as $type) {
            $stats[$type->getValue()] = [
                'count' => $this->likeService->countLikesByType($post, $type),
                'emoji' => $type->getEmoji(),
                'label' => $type->getLabel(),
            ];
        }
        
        return $stats;
    }

    public function stats(Post $post)
    {
        return response()->json($this->getReactionStats($post));
    }

    public function myReactions(Request $request)
    {
        $user = $request->user();
        $type = CustomLikeType::tryFrom($request->input('type'));

        if ($type) {
            $reactions = $this->likeService->getLikerLikesByType($user, $type);
        } else {
            $reactions = $this->likeService->getLikerLikes($user);
        }

        return response()->json($reactions);
    }
}
bash
php artisan vendor:publish --tag=likes-migrations
bash
php artisan migrate