Installation
composer require xlabs/likebundle
Publish the bundle's configuration and migrations:
php artisan xlabs:like:install
Database Setup
Run migrations to create the likes table:
php artisan migrate
Basic Usage
Add the Likeable trait to your model (e.g., Post.php):
use XLabs\LikeBundle\Traits\Likeable;
class Post extends Model
{
use Likeable;
}
First Like Action Toggle a like on a post in a controller:
$post = Post::find(1);
$post->toggleLike(auth()->id());
Displaying Likes Use the provided helpers in Blade:
@like($post, 'like-button', 'liked')
Model Integration
Likeable trait.likes() relationship and toggleLike() method.API Endpoints
Create a dedicated API route for likes (e.g., like/{model}/{id}):
Route::post('like/{model}/{id}', [LikeController::class, 'toggle']);
Real-Time Updates Use Laravel Echo + Pusher to broadcast like events:
// In LikeController
broadcast(new LikeEvent($model, $userId, $liked));
Batch Processing
Use XLabs\LikeBundle\Services\LikeService to manage bulk operations:
$service = app(LikeService::class);
$service->bulkToggle($postIds, auth()->id());
LikeRequest class to add custom validation rules.auth middleware.Cache::remember("post:{$post->id}:likes", now()->addHours(1), fn() => $post->likesCount());
Model Configuration
XLabs\LikeBundle\Traits\Likeable before defining relationships.public $likeableType = 'App\Models\YourModel';.Migration Conflicts
likes table already exists, manually adjust the migration or drop it first:
php artisan migrate:fresh --env=testing
Event Listeners
Liked and Unliked events. Subscribe to them in EventServiceProvider:
protected $listen = [
'XLabs\LikeBundle\Events\Liked' => [
YourListener::class,
],
];
Performance
withCount('likes') instead:
$posts = Post::withCount('likes')->get();
Log Like Actions: Extend the LikeService to log actions:
public function toggleLike($model, $userId, $liked)
{
\Log::info("Like toggled", [
'model' => $model->id,
'user' => $userId,
'action' => $liked ? 'liked' : 'unliked',
]);
// ... rest of the logic
}
Check for Duplicate Entries: Use unique() in migrations or add a composite unique index:
Schema::table('likes', function (Blueprint $table) {
$table->unique(['likeable_type', 'likeable_id', 'user_id']);
});
Custom Like Logic
Override the toggleLike() method in your model:
public function toggleLike($userId, $force = null)
{
if ($this->isProUser($userId)) {
return $this->forceLike($userId);
}
return parent::toggleLike($userId, $force);
}
Custom Storage
Replace the default Like model by binding a custom implementation in AppServiceProvider:
public function register()
{
$this->app->bind(
XLabs\LikeBundle\Models\Like::class,
CustomLikeModel::class
);
}
UI Customization
Override the Blade directives in AppServiceProvider:
Blade::directive('like', function ($expression) {
return "<?php echo XLabs\LikeBundle\Blade::like($expression); ?>";
});
How can I help you explore Laravel packages today?