Add Likes, Bookmarks, Favorites, and Other Marks in your Application With Laravel Markable

Packages

April 12th, 2022

laravel-markable-featured.png

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:

1namespace App\Models;
2 
3use Illuminate\Database\Eloquent\Model;
4use Maize\Markable\Markable;
5use Maize\Markable\Models\Like;
6 
7class Course extends Model
8{
9 use Markable;
10 
11 protected $fillable = [
12 'title',
13 'description',
14 ];
15 
16 protected static $marks = [
17 Like::class,
18 ];
19}

With that model in place, here's what it looks like to manage marks using this package:

1use App\Models\Course;
2use Maize\Markable\Models\Like;
3 
4// marks the course liked for the given user
5Like::add($course, $user);
6 
7// unmarks the course liked for the given user
8Like::remove($course, $user);
9 
10// toggles the course like for the given user
11Like::toggle($course, $user);
12 
13// returns whether the given user likes a course or not
14Like::has($course, $user);
15 
16// returns how many users like a course
17Like::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:

1// All course models with a like from the given user
2Course::whereHasLike(
3 auth()->user()
4)->get();
5 
6// All post models with a 'heart' reaction from the given user
7Post::whereHasReaction(
8 auth()->user(),
9 'heart'
10)->get();

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners