skip to Main Content

i am new to Laravel and i am working on a blog/post project with likes and comments.

Now i would like to display/count all likes from all post that was made by a user.
So for example: user 1 made post 1 and user 2, user 3 liked post 1, should be 2 likes displayed on user 1 profile page. That is not the case right now and i don’t know where i messed up with the SQL statement below.

Blogs table:
Likes table:

Controller:

    public function getProfilePage()
    {

        $user = Auth::user();
        $blog = Blog::where('user_id', $user->id)->get();
        $likes = Like::where('likeable_id', $blog)->get();
        $comments = DB::table('comments')->where('user_id', $user->id)->get();

        return view('auth.profile', compact('user', 'blog', 'likes', 'comments'));
    }

And in Blade file i count($likes)

now i know the problem is somewhere in $blog, but to my knowledge this statement should be correct. Still it’s returning 0 likes.

Models:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use AppContractsLikeable;
use AppModelsConcernsLikes;
use UsamamuneerchaudharyCommentifyTraitsCommentable;

class Blog extends Model implements Likeable
{
    use HasFactory;
    use Likes;
    use Commentable;

    protected $fillable = [
        'title',
        'beschrijving',
        'image',
    ];

    public function user()
    {
        return $this->belongsTo(User::class);
    }
}
<?php

namespace AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;

class Like extends Model
{
    use HasFactory;

    public function user()
    {
        return $this->belongsTo(User::class)->withDefault();
    }

    public function likeable()
    {
        return $this->morphTo();
    }
}

2

Answers


  1. Looks like you are using a polymorphic relationship between blogs and likes. Check that you have made this relationship correctly in the models. The documentation for it is here. Laravel relationship documentation

    You should have a morph many function in your blog model and morphto in your likeable. The comments in the example and the documentation explains it well

    Login or Signup to reply.
  2. Out of my head I’m not sure whether there isnt a conversion which will take care of it, but it might be possible you need to specify blog $blog->id.

    $blog = Blog::where('user_id', $user->id)->first();
    $likes = Like::where('likeable_id', $blog->id)->get();
    

    instead of

    $blog = Blog::where('user_id', $user->id)->get();
    $likes = Like::where('likeable_id', $blog)->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search