Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

guillaumebriday/laravel-blog

1797 stars
5 code files
View guillaumebriday/laravel-blog on GitHub

database/migrations/2017_11_15_003340_create_likes_table.php

Open in GitHub
use 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 GitHub
use 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 GitHub
use App\Concern\Likeable;
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
use Likeable;
}

app/Concern/Likeable.php

Open in GitHub
use 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 GitHub
use 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();
}
}

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.