Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel / AJAX Like Button Error: Request failed with status code 404

I'm very new to Laravel, AJAX etc. I am a student working on a Twitter type project and this is my first stack question ever made. I've tried to look for answers but the code that my teacher has helped me with is very different from other examples. I'm pretty sure that my problem is with the unlike method inside of my "Tweet Controller"... Any help is greatly appreciated! Hopefully I have provided enough information and hopefully this can help others in the future :)

This is my error:[1]: https://i.sstatic.net/zkxsd.png

POST http://localhost:8000/tweets/19/unlike 404 (Not Found)
Uncaught (in promise) Error: Request failed with status code 404
at createError (app.js:14253)
at settle (app.js:35706)
at XMLHttpRequest.handleLoad (app.js:14127)

This is my likes table / migration

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateLikesTable extends Migration
{
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('likes', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('tweet_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('likes');
}
}

This is my Tweet Controller

public function like($id){


     $like = Like::create([
         'user_id'=>auth()->id(),
         'tweet_id'=> $id

     ]);
     if($like){
         return json_encode(array('status' => 'success'));

     }
     return json_encode(array('status' => 'failed'));

 }

 public function unlike($id){
     $like = Like::delete([
         'user_id'=>auth()->id(),
         'tweet_id'=> $id

     ]);

    if($like){
        return json_encode(array('status' => 'success'));
    }
}

This is my Web Routes

Route::post('tweets/{tweet}/like', 'TweetController@like');
Route::delete('tweets/{tweet}/like', 'TweetController@unlike');

This is my Model

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

public function likedByCurrentUser(){
    $userId=auth()->id();

    //like boolean
    $like = $this->likes->first(function($v) use ($userId){
        //$v is a reference to the single like
        return $v->user_id == $userId;
    });

    //if the user has liked a post
    if($like){
       return true;
   }
   return false;

}

This is my Vue Component:

<script>
export default {
    name: 'likeButton',
    props: ['likeCount','hasLiked','tweetId','csrf'],

     mounted(){
         this.dataLikeCount = this.likeCount;
         this.dataHasLiked = this.hasLiked;
     },
        data(){
            return{
                dataLikeCount:0,
                dataHasLiked:false

            }
        },

        methods:{
            doLike(){
                var type='like';

                if(this.dataHasLiked){
                    type='unlike'
                }

                axios({
                    method:'POST',
                    url:'/tweets/' + this.tweetId + '/'+ type,
                    headers:{
                        'X-CSRFToken':this.csrf
                    },
                    json: true

                    }).then((response) => {
                        if(response.data.status == 'success'){
                            // response was successful (regardless of type)
                            return true
                            // if type is like
                                // add one to like count, set hasLiked to true
                                if(type == 'like'){
                                    this.dataLikeCount++
                                }
                            // if type is unlike
                                // deduct one from like count, set hasLiked to false
                                if(type =='unlike'){
                                    return false
                                    this.dataLikeCount--
                                }
                        }
                    });
                }
            }
        }
</script>

<template>
<div>
    <button type="submit"
    :class="{'btn btn-link':dataHasLiked}"
    @click="doLike">

          <i class="star"></i>
          Like {{ dataLikeCount }}

    </button>
</div>


</template>
like image 693
user3069007 Avatar asked Dec 27 '25 22:12

user3069007


1 Answers

You dont have a matching route for unlike.

Change

Route::delete('tweets/{tweet}/like', 'TweetController@unlike');

To

Route::delete('tweets/{tweet}/unlike', 'TweetController@unlike');
like image 179
Brian Lee Avatar answered Dec 30 '25 14:12

Brian Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!