简体   繁体   中英

How do I remove the one "like" from that particular user?

Trying do create a "like system" for a simple application with Laravel and Livewire. I have managed to add likes, but I only want the user to be able to add one (1) like to a post. At the moment a user can add as many likes as he or she wants.

This is my current function to store likes:

    public function storeLike()
    {
        // Check if the user already has liked the post
        if($this->collection->likes()->exists()){
            return $this->collection->likes()->delete();
        }

        // If not, add one like to the db
        $like = $this->collection->likes()->make();
        $like->user()->associate(auth()->user());

        // Save the like
        $like->save();
    }

And the part that im struggling with is:

        if($this->collection->likes()->exists()){
            return $this->collection->likes()->delete();
        }

It deletes all the likes for that post. So how can a disassociate, detach that like if it exists?

This is how I have made the collection:

        $collection = collect();

        $posts = Post::search('topic', $this->search)->with(['user'])->latest()->get();
        $urls = Urls::search('topic', $this->search)->with(['user'])->latest()->get();
        $news = News::search('topic', $this->search)->latest()->get();

        /** Push posts to the collection */
        foreach ($posts as $post) $collection->push($post);
        /** Push urls to the collection */
        foreach ($urls as $item) $collection->push($item);
        /** Push news to the collection */
        foreach ($news as $item) $collection->push($item);

I think the toggle (see docs ) method could be very handy.

Let's assume we're building a component for a model called Post .

Livewire

public function clickedLike() {
    $this->post->likes()->toggle(Auth::user());
}

Template

<button wire:click="clickedLike">
    <3
</button>

Model

class Post extends Model {
    public function likes() {
        return $this->hasMany(User::class, 'likes')
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM