// In post model are we are checking whether user has liked it:
// contains is a collection method which allows to look at the inside of the collection
// with collectiong you are looking at a particular key (user_id), and checking if the $user->id is within the collection
// then it will return a true or false
// POST MODEL:
public function likedBy(User $user){
return $this->likes->contains('user_id', $user->id);
}
//POSTLIKECONTROLLER
public function store($id, Request $request){
// this is activating when you press the submit button for like
$this->middleware(['auth']);
$post = Post::find($id);
if ($post->likedBy($request->user())){
return back();
}
$post->likes()->create([
'user_id' => $request->user()->id,
]);
return back();
Comments