Skip to content

Instantly share code, notes, and snippets.

@whoisthisstud
Last active September 26, 2024 21:10
Show Gist options
  • Select an option

  • Save whoisthisstud/146e422741812731405dfcdcf4573fcf to your computer and use it in GitHub Desktop.

Select an option

Save whoisthisstud/146e422741812731405dfcdcf4573fcf to your computer and use it in GitHub Desktop.
Laravel Bookmarking Traits
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('bookmarks', function (Blueprint $table) {
$table->increments('id');
$table->foreignId('user_id')->nullable();
$table->morphs('bookmarkable');
$table->timestamps();
$table->index('bookmarkable_id');
$table->index('bookmarkable_type');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('bookmarks');
}
};
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Bookmark extends Model
{
use HasFactory;
public function bookmarkable()
{
return $this->morphTo();
}
}
<?php
namespace App\Traits\Bookmarks;
use App\Models\Bookmark;
use Illuminate\Support\Facades\Auth;
trait Bookmarkable
{
public function bookmark()
{
$bookmark = new Bookmark();
$bookmark->user_id = Auth::id();
$this->bookmarks()->save($bookmark);
}
public function toggleBookmark(): void
{
$bookmark = Bookmark::query()
->where('bookmarkable_type', '=', $this->getMorphClass())
->where('bookmarkable_id', '=', $this->id)
->where('user_id', '=', Auth::id())
->first();
!$bookmark ? $this->bookmark() : $bookmark->delete();
}
public function wasBookmarkedBy($user): bool
{
if ( is_null($user) ) {
return false;
}
$bookmark = Bookmark::query()
->where('bookmarkable_type', '=', $this->getMorphClass())
->where('bookmarkable_id', '=', $this->id)
->where('user_id', '=', $user->id)
->count();
return $bookmark > 0 ? true : false;
}
public function bookmarks()
{
return $this->morphMany('App\Models\Bookmark', 'bookmarkable');
}
public function timesBookmarked()
{
return $this->bookmarks()->count();
}
public function getTimesBookmarkedAttribute()
{
return $this->timesBookmarked();
}
}
<?php
namespace App\Traits\Bookmarks;
use App\Models\Bookmark;
class HasBookmarks
{
public function personalBookmarks()
{
return Bookmark::query()
->where('user_id', $this->id)
->get();
}
public function hasBookmarks()
{
return $this->personalBookmarks()->count() > 0
? true
: false;
}
public function getBookmarksAttribute()
{
return $this->personalBookmarks();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment