Trait for Laravel Eloquent models to allow easy implementation of a "like" or "favorite" or "remember" feature.
Based heavily on rtconner/laravel-likeable.
composer require sugar/laravel-favorites
'providers' => [
\Sugar\Favorites\FavoritesServiceProvider::class,
],
php artisan vendor:publish --provider="Sugar\Favorites\FavoritesServiceProvider"
php artisan migrate
class Article extends \Illuminate\Database\Eloquent\Model {
use \Sugar\Favorites\Likeable;
}
After installation, the config file is located at config/favorites.php
You can :
- enable session fallback for likes
- define the lifetime (in minutes) for the command favorites:clean
- define if the command favorites:clean should delete only session likes
$article->like(); // like the article for current user / session
$article->like($myUserId, $false); // like the article for specific user
$article->unlike(); // like the article for current user / session
$article->unlike($myUserId, $false); // unlike the article for specific user
$article->likeCount; // get count of likes
$article->getLikeCountByDate('2012-01-30'); // Count likes for a specific date
$article->getLikeCountByDate('2012-01-30', '2016-01-30'); // Count likes for a date range
$article->liked(); // check if currently logged in user or session user liked the article
$article->liked($myUserId, $false);
$article->likes; // Iterable Illuminate\Database\Eloquent\Collection of existing likes
Article::whereLikedBy()->get(); // for the current user / session
Article::whereLikedBy($myUserId, false)->get(); // for a specific user
Because someone's favorite could be 'outdated' and not representative anymore.
There is a command for that. The time after which a like is outdated can be set in the config, also you can define if it should only delete session likes
php artisan favorites:clean
In order to convert session likes to user likes (for example after a visitor registers on you site) you need to use the Helper class.
This workaround is nescessary because session id's are regenerated after login/logout.
class AuthController extends Controller {
use AuthenticatesAndRegistersUsers {
login as traitlogin;
register as traitregister;
}
use ThrottlesLogins;
public function login(Request $request, \Sugar\Favorites\Helper $helper) {
$session_id = $helper->sessionId();
$return = $this->traitlogin($request);
if(Auth::check()){
$helper->convertSessionToUserLikes($session_id, Auth::user()->id);
}
return $return;
}
public function register(Request $request, \Sugar\Favorites\Helper $helper){
$session_id = $helper->sessionId();
$return = $this->traitregister($request);
if(Auth::check()){
$helper->convertSessionToUserLikes($session_id, Auth::user()->id);
}
return $return;
}
...
}
- Gregory Claeyssens - http://sugar.gent
- Robert Conner - http://smartersoftware.net