The steps are very straightforward just follow along and you will have it implemented in a matter of minutes. For this case scenario, imagine that you have Post or Article models and you want the user to like or dislike it, this package does exactly that.
Installation
Require the package to your app using composer.
composer require rtconner/laravel-likeable
Migrate Table
This package comes with a migration file that contains the table structure to save the liked model.
php artisan migrate
Setup Model
To allow the user to like the particular model, make use of the Likeable trait from the package itself.
class Post extends \Illuminate\Database\Eloquent\Model { use \Conner\Likeable\Likeable; }
Implementation
To like the model (in this case post model) call the like method that's made available by the trait.
$post->like(); // like the article for current user $post->like($userId); // pass in your own user id $post->like(0); // just add likes to the count, and don't track by user
$post->unlike(); // remove like from the article $post->unlike($userId); // pass in your own user id $post->unlike(0); // remove likes from the count -- does not check for user
Count total number of Likes
To count the total number of likes, do access the likeCount property
$post->likeCount; // get count of likes
$post->likes; // Iterable Illuminate\Database\Eloquent\Collection of existing likes
$post->liked(); // check if currently logged in user liked the article $post->liked($userId);
Performance Enhancement
To better enhance the performance, do eager load the likes relation by using with key.
Post::whereLikedBy($userId) // find only articles where user liked them ->with('likeCounter') // highly suggested to allow eager load ->get();