PHP code example of binafy / laravel-reactions

1. Go to this page and download the library: Download binafy/laravel-reactions 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/ */

    

binafy / laravel-reactions example snippets

 >= 8.1

use Binafy\LaravelReaction\Traits\Reactor;

class User extends Authenticatable
{
    use Reactor;
}

use Binafy\LaravelReaction\Contracts\HasReaction;
use Binafy\LaravelReaction\Traits\Reactable;

class Post extends Model implements HasReaction
{
    use Reactable;
}

use Binafy\LaravelReaction\Enums\LaravelReactionTypeEnum;

$user = User::find(1);
$post = Post::find(1);

// Using enum reaction types
$user->reaction(LaravelReactionTypeEnum::REACTION_ANGRY, $post);

// Using custom string reaction types
$user->reaction('love', $post);

$post = Post::find(1);
$user = User::find(1);

// Specify the user explicitly
$post->reaction('like', $user);

// Use the currently authenticated user
$post->reaction('like'); // Uses auth()->user()

$post = Post::find(1);
$user = User::find(1);

// Check if a specific user reacted
if ($post->isReacted($user)) {
    echo "User has reacted to this post";
}

// Check if the currently authenticated user reacted
if ($post->isReacted()) {
    echo "You have reacted to this post";
}

$post = Post::find(1);

// Count specific reaction type
$likeCount = $post->getReactCountByType('like');
$angryCount = $post->getReactCountByType(LaravelReactionTypeEnum::REACTION_ANGRY);

$post = Post::find(1);

// Returns collection with type => count pairs
$reactionCounts = $post->getReactionsWithCount();
// Example result: ['like' => 5, 'love' => 3, 'angry' => 1]

$post = Post::find(1);

// Get all users who reacted to this post
$reactors = $post->getReactors();

$user = User::find(1);
$post = Post::find(1);

// Remove specific reaction type
$user->removeReaction('like', $post);

// Or from the reactable side
$post->removeReaction('like', $user);
$post->removeReaction('like'); // For authenticated user

$user = User::find(1);
$post = Post::find(1);

// Remove all reactions by the user on this post
$user->removeReactions($post);

// Or from the reactable side
$post->removeReactions($user);
$post->removeReactions(); // For authenticated user
shell
php artisan vendor:publish --tag="laravel-reactions-config"
shell
php artisan vendor:publish --tag="laravel-reactions-migrations"
shell
php artisan vendor:publish --provider="Binafy\LaravelReaction\Providers\LaravelReactionServiceProvider"