Polymorphic Likes

1
Лайки для моделей через Polymorphic Relationships.

app/Models/Traits/HasLikes.php
                            
<?php
 
namespace App\Models\Traits;
 
use App\Models\Like;
 
trait HasLikes
{
public function likes()
{
return $this->morphMany(Like::class, 'likeable');
}
}
app/Models/Like.php
                            
<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
 
class Like extends Model
{
use HasFactory;
 
protected $fillable = ["user_id"];
 
/**
* Get the parent likeable model
*/
public function likeable()
{
return $this->morphTo();
}
 
public function user()
{
return $this->belongsTo(User::class);
}
}
app/Models/Post.php
                            
<?php
 
namespace App\Models;
 
use App\Models\Traits\HasLikes;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
use HasLikes;
 
protected $fillable = [
"name", "text"
];
}
database/migrations/2021_07_05_112010_create_likes_table.php
                            
<?php
 
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
 
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->id();
 
$table->integer("likeable_id");
$table->string("likeable_type");
 
$table->foreignId("user_id")->constrained()->cascadeOnDelete()->cascadeOnUpdate();
 
$table->timestamps();
});
}
 
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}