Search by

pharaonic / laravel-favorites

Pharaonic

Polymorphic favorites for Laravel Eloquent models, with database-enforced uniqueness and explicit changed-state results.

Package info

github.com/Pharaonic/laravel-favorites

Documentation

pkg:composer/pharaonic/laravel-favorites

Fund package maintenance!

MoamenEltouny

Buy Me A Coffee

Statistics

Installs: 14

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

13.0.0 2026-11-12 18:35 UTC

This package is auto-updated.

Last update: 2026-11-12 18:35:20 UTC


README

PHP Version : 8.3 | 8.4 | 8.5 Laravel Version : 13.x License Build
Source Packagist Version Packagist Downloads

Polymorphic favorites for Eloquent models, kept unique by the database.


Installation

composer require pharaonic/laravel-favorites
php artisan migrate

The service provider is registered automatically, and migrate creates the favorites table. Publish the migration only to change it (--tag=favorites-migrations), and the configuration only to rename the table or turn off cleanup on delete:

php artisan vendor:publish --tag=favorites-config

Usage

Add CanFavorite to the model that favorites (it does not have to be a user) and HasFavorites to the model that is favorited. A model can use both.

use Illuminate\Foundation\Auth\User as Authenticatable;
use Pharaonic\Laravel\Favorites\Concerns\CanFavorite;

class User extends Authenticatable
{
    use CanFavorite;
}
use Illuminate\Database\Eloquent\Model;
use Pharaonic\Laravel\Favorites\Concerns\HasFavorites;

class Post extends Model
{
    use HasFavorites;
}
$user->favorite($post);       // true: this call created the favorite
$user->favorite($post);       // false: it already existed
$user->hasFavorited($post);   // true
$user->unfavorite($post);     // true: this call removed it, false when there was none
$user->toggleFavorite($post); // the new state: true when favorited

$post->favoriteBy($user);     // same as $user->favorite($post)
$post->unfavoriteBy($user);   // same as $user->unfavorite($post)
$post->favoritedBy($user);    // same as $user->hasFavorited($post)

Post::withCount('favorites')->with('favorites.favoriter')->get();
Post::whereFavoritedBy($user)->latest()->paginate();
$user->givenFavorites()->with('favoritable')->latest()->get();

Documentation

Full documentation: Laravel Favorites Documentation.

Support & Security

See SUPPORT.md and SECURITY.md. Contributions are welcome; see CONTRIBUTING.md.

License

MIT. See LICENSE.