add likes to post (laravel)

Issue

I have a blog built with laravel.
and I want to add likes to my posts.
so I created a Like model with a likes table.

this is what i have done in my Like model

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

in my Post and User models

    public function likes(){
        return $this->hasMany(Like::class);
    }

and my migration file for likes table


        Schema::create('likes', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->foreign('post_id')->references('id')->on('posts');
            $table->foreign('user_id')->references('id')->on('users');
            $table->boolean('value');
            $table->timestamps();
        });

I want to set the values in my controller on this way!

public function liker($postID, $userID, $value){
        $like = new Like([
            'post_id' => $postID,
            'user_id' => $userID,
            'value' => $value
        ]);
        $like->save();
        return redirect()->back();
    }

but the view return 419 error page. (Page Expired)

and also no changes (no row) adds to my database(likes table)!
can you help me?

Solution

you dont need value on a like, if it exists, it’s a “like” and you should use is as a pivot table (you already have 2 foreign IDs in it)

Schema::create('likes', function (Blueprint $table) {
    $table->unsignedInteger('post_id');
    $table->unsignedInteger('user_id');
    $table->foreign('post_id')->references('id')->on('posts');
    $table->foreign('user_id')->references('id')->on('users');
    $table->tinyInteger('is_dislike')->default(0);
    $table->timestamps();
});

then declare the relation between Post and User

Post

public function votedUsers(){ //or simply likes
    return $this->belongsToMany(User::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}

User

public function votedPosts(){
    return $this->belongsToMany(Post::class, 'likes')->withPivot('is_dislike')->withTimestamps();
}

Next to create a like just do it like this

public function liker($postId, $userId, $value){
    $user = User::findOrFail($userId); //or use auth()->user(); if it's the authenticated user
    $user->votedPosts()->attach($postId);
    return redirect()->back();
}

to Remove a like use detach($postId) instead.

For dislike

$user->votedPosts()->attach($postId, ['is_dislike' => 1]);

Answered By – N69S

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published