Skip to content

Instantly share code, notes, and snippets.

@kfirba
Created February 9, 2020 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfirba/3b1a789cdca9967f511cd2c932d463d8 to your computer and use it in GitHub Desktop.
Save kfirba/3b1a789cdca9967f511cd2c932d463d8 to your computer and use it in GitHub Desktop.
Followables
<?php
namespace App;
trait CanBeFollowed
{
public function isFollowedBy($user)
{
if ($this->relationLoaded('followers')) {
return $this->followers->first(function ($follower) use ($user) {
return $follower->is($user);
}) !== null;
}
return $this->followers()->where('user_id', $user->id)->exists();
}
public function followers()
{
return $this->morphToMany(User::class, 'followable', 'followables')->withPivot('created_at');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
trait CanFollow
{
public function follow($followable)
{
return $this->followings(get_class($followable))->syncWithoutDetaching([
$followable->id => ['created_at' => now()],
]);
}
public function unfollow($followable)
{
return $this->followings()->detach($followable);
}
public function isFollowing($followable)
{
if ($this->relationLoaded('followings')) {
return $this->followings->first(function ($following) use ($followable) {
return $following->is($followable);
}) !== null;
}
return $this->followings()
->where('followable_id', $followable->id)
->where('followable_type', get_class($followable))
->exists();
}
public function followings($class = User::class)
{
return $this->morphedByMany($class, 'followable', 'followables');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFollowablesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('followables', function (Blueprint $table) {
$table->unsignedBigInteger('user_id')->index();
$table->morphs('followable');
$table->timestamp('created_at')->nullable();
$table->primary(['user_id', 'followable_type', 'followable_id']);
$table->index(['followable_type', 'followable_id', 'user_id']);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('followables');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment