Add Likes, Bookmarks, Favorites, and Other Marks in your Application With Laravel Markable
Published on by Paul Redmond
Laravel Markable is a package to Integrate likes, bookmarks, favorites, reactions, and custom-made marks into your application.
The basic usage is adding a Markable
trait and types of "marks" you want to allow for a given model. For example, if you have a Course
model and you want to let users like the course:
namespace App\Models; use Illuminate\Database\Eloquent\Model;use Maize\Markable\Markable;use Maize\Markable\Models\Like; class Course extends Model{ use Markable; protected $fillable = [ 'title', 'description', ]; protected static $marks = [ Like::class, ];}
With that model in place, here's what it looks like to manage marks using this package:
use App\Models\Course;use Maize\Markable\Models\Like; // marks the course liked for the given userLike::add($course, $user); // unmarks the course liked for the given userLike::remove($course, $user); // toggles the course like for the given userLike::toggle($course, $user); // returns whether the given user likes a course or notLike::has($course, $user); // returns how many users like a courseLike::count($course);
The Like
model is built-in to the package, but you can also build custom mark models, such as Pledge
that allows a user to pledge a donation to a cause.
The package includes various mark types out-of-the-box, including:
- Bookmark
- Favorite
- Like
- Reaction
On the other side of adding a Like for a user, you might what to list all likes for a given user so they can see what courses they've liked:
// All course models with a like from the given userCourse::whereHasLike( auth()->user())->get(); // All post models with a 'heart' reaction from the given userPost::whereHasReaction( auth()->user(), 'heart')->get();
You can learn more about this package, get full installation instructions, and view the source code on GitHub.