feknuolis feknuolis - 4 months ago 24
PHP Question

Check if user liked post Laravel

I need to check if user liked the post and dont let like it anymore. The problem is that with my code when one of the users likes the post, I cannot like it with another user. I don't know why.

Controller:

$posts = Post::orderBy('created_at', 'desc')->paginate(10);
foreach($posts as $p){
foreach ($p->like as $like){
$like = Like::where('user_id', '=', Auth::user()->id)->get();
}
}


Post.php:

public function user(){
return $this->belongsTo('App\User');
}

public function like()
{
return $this->hasMany('App\Like');
}


Like.php:

public function user()
{
return $this->belongsTo('App\User');
}

public function post()
{
return $this->belongsTo('App\Post');
}


User.php:

public function post(){
return $this->hasMany('App\Post');
}

public function like(){
return $this->hasMany('App\Like');
}


HTML

@if($like)
<i class="fa fa-thumbs-o-up liked pull-right" aria-hidden="true"></i>
@else
<a href="/like/{{$p->id}}">
<i class="fa fa-thumbs-o-up likeBtn pull-right" aria-hidden="true"></i></a>
@endif

Answer

Don't do the loop in controller. Do it in view(blade)

Edited Controller

$posts = Post::orderBy('created_at', 'desc')->paginate(10);
$likes = Like::select('post_id')->where('user_id',Auth::user()->id)->get();
$likeArr=array_flatten($likes->toArray()); //convert multidimensional array to single array for easy access
return view('yourview',['posts'=>$posts,'likes'=>$likeArr]);

VIEW

@foreach($posts as $p)
    @if(in_array($p->id,$likes))
        <i class="fa fa-thumbs-o-up liked pull-right" aria-hidden="true"></i>
    @else
        <a href="/like/{{$p->id}}">
            <i class="fa fa-thumbs-o-up likeBtn pull-right" aria-hidden="true"></i>
        </a>
    @endif
@endforeach