Ibe

How to create likes??

Posted 1 year ago by Ibe

Hi there, I am having a problem with my likes system. So I am able to store my likes without a problem, but what I would like if when a user likes a post, its shows the 'unlike' button.

Anyone having an idea how you can do this?

Route:

Route::post('/posts/{post}/likes', '[email protected]');

Like controller:

public function store(Post $post)
  {

    Like::create([
      'post_id' => $post->id,
      'user_id' => Auth::user()->id
    ]);

    return back();
  }

post model:

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

user model:

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

like model:

protected $fillable = [
      'post_id', 'user_id'
  ];


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

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

show.blade.php

@if ($post->like)
    You liked this post!
  @else

  <form class="" action="/user/posts/{{$post->id}}/likes" method="post">
    {{csrf_field()}}

        <input type="submit" value="LIKE" class="button is-primary">

  </form>

  @endif 

database tables:

        $table->increments('id');
            $table->integer('post_id');
            $table->integer('user_id');
            $table->softDeletes();
            $table->timestamps();

-King regards

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.