-
database/migrations/2017_11_15_003340_create_likes_table.php
Open in GitHubuse Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateLikesTable extends Migration { public function up() { Schema::create('likes', function (Blueprint $table) { $table->nullableMorphs('likeable'); }); } }
-
app/Models/Like.php
Open in GitHubuse Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\MorphTo; class Like extends Model { public function likeable(): MorphTo { return $this->morphTo(); } }
-
app/Models/Post.php
Open in GitHubuse App\Concern\Likeable; use Illuminate\Database\Eloquent\Model; class Post extends Model { use Likeable; }
-
app/Concern/Likeable.php
Open in GitHubuse App\Models\Like; use Illuminate\Database\Eloquent\Relations\morphMany; trait Likeable { public function likes(): morphMany { return $this->morphMany(Like::class, 'likeable'); } public function like() { if ($this->likes()->where('author_id', auth()->id())->doesntExist()) { return $this->likes()->create(['author_id' => auth()->id()]); } } }
-
app/Http/Controllers/Api/V1/PostLikeController.php
Open in GitHubuse App\Http\Controllers\Controller; use App\Models\Post; use Illuminate\Http\Request; class PostLikeController extends Controller { public function store(Request $request, Post $post) { return $post->like(); } }