1

我在 Laravel 5.6 中使用这个包我的项目中添加喜欢系统。

我已经根据他们的文档更新了模型。但是,我对如何使用这个包感到困惑。

我添加了以下尝试,当他访问链接时,将登录用户添加到特定的文章喜欢列表中。

public function show(ArticleCategory $articlecategory, $slug)
{
    $categories = ArticleCategory::all();
    $article = Article::where('slug', $slug)->first();
    $user = User::first();
    $user->addFavorite($article);
    return view('articles.show', compact('article', 'categories'));
}

在我的用户仪表板中,我可以提取用户喜欢的所有文章

$user = Auth::user();
$favoritearticles = $user->favorite(Article::class);

但我正在寻找一种功能,我在文章页面上有一个按钮,当登录的用户点击它时,他会被添加到喜欢列表中。我之前没有尝试过,所以一直停留在这一点上。

我换了

$user->addFavorite($article);

$user->toggleFavorite($article);

但这只是切换收藏夹列表。我的意思是当我访问该链接一次时,登录的用户会被添加到喜欢列表中。当我第二次访问该链接时,登录的用户会从喜欢列表中删除。循环重复。

谁能向我解释如何使用按钮实现类似的功能?

4

2 回答 2

2

你快到了,你必须添加一个button,点击你会触发一个 AJAX 请求到服务器来执行你想要的,而不刷新页面,这里是一个例子:

首先,您将添加一个按钮并为其指定 ID 或类:

<button class="like">Like</button>

然后当你点击它的那一刻,你会调用url你需要用你的函数的路由替换它,

然后你必须像这样声明一个方法:

public function like($slug)
{
    $article = Article::where('slug', $slug)->first();
    $user = \Auth::user(); //to get authenticated user...
    $user->toggleFavorite($article); // toggle so if u already like it u remove it from the liked table
    return response()->json(['status': 1])
}

当然,将路线添加到您的routes.php

Router::get('like/{slug}',"ArticleController@like");

然后添加函数(这里使用jQuery)来挂钩AJAX调用

$('.like').on('click', function(){
  $.ajax({
    type: "GET",
    url: 'wwww.example.com/articles/slug',
    data: {slug: 'the slug'},
    success: function(data){
      alert('its done')
    },
  });
})
于 2018-03-05T09:49:08.657 回答
0

在您的文章页面中创建一个带有按钮的表单

<form action="{{url('favorite/{$post->id}')}}" method="post">
@if($post->isFavorited())
<button type="submit">Remove from favorite</button>
@else
<button type="submit">Add to favorite</button>
@endif
</form>

创建最喜欢的路由和控制器

Router::post('favorite/{id}',"ArticleController@toggleFavorite");


public function toggleFavorite($id) {
 $article = ArticleCategory::find($id);//get the article based on the id
 Auth::user()->toggleFavorite($article);//add/remove the user from the favorite list
 return Redirect::to('article/{$id}');//redirect back (optionally with a message)
}
于 2018-03-05T09:48:06.733 回答