Search code examples
sqlmysqllaravelcountlaravel-blade

Laravel SQL statement is returning null


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 App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Contracts\Likeable;
use App\Models\Concerns\Likes;
use Usamamuneerchaudhary\Commentify\Traits\Commentable;

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 App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Like extends Model
{
    use HasFactory;

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

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

Solution

  • 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();