有人能一步一步告诉我如何在我的应用程序中创建一个类似功能的按钮吗?解释一下它是如何工作的,这样我就不必依赖你的代码,并且可以自己创建自己的类似按钮。我希望有人能指导我,因为我不知道这个东西是如何工作的,我必须创建多少数据库表,或者我应该使用javascript。我的应用程序可以显示数据库中的所有帖子,这是我迄今为止的代码。
来自我的控制器:
public function dashboard()
{
$mytime = Carbon'Carbon::now();
$user = Auth::user();
$posts = Post::where('reviewed', '=' , 1)->orderBy('created_at', 'DESC');
$url = asset('img/logo.gif');
$this->layout->content = View::make('interface.dashboard',
array('posts' => $posts->paginate(9)))
->with('img', $url)
->with('user', $user)
->with('date', $mytime);
}
以及我的观点:
<div class="dashboard">
@foreach (array_chunk($posts->getCollection()->all(),4) as $row)
<div class="row">
@foreach($row as $post)
<article class="col-md-4 effect4" class="dash-box">
<p></p>
<div><img src="{{ asset('img/' . $post->image) }}" /></div>
<b><a href="{{ URL::action('LoginUsersController@viewPost' , array('id' => $post->id))}}">{{$post->title}}</a></b>
<hr>
<d>{{$post->created_at->toFormattedDateString()}}</d>
</article>
@endforeach
</div>
@endforeach
<div class="page">
{{$posts->appends(Request::only('difficulty'))->links()}}
</div>
</div>
您还没有指定类似的内容是针对用户还是针对帖子,我猜是针对帖子。在这种情况下,您不应该创建新表,因为您可以在Post表中添加"number_of_like"列。
然后在@foreach中创建一个类似按钮($row作为$post),它看起来像这样:
{{ Form::open(['method' => 'POST', 'route' => [ 'post_path', $post->id ] ) }}
<button type="submit" >Like</button>
{{ Form::close() }}
在上面,您将post-id发布到post_path,然后在您的routes.php:中定义该post_path
Route::post('post/{id}', [
'as' => 'post_path',
'uses' => 'PostController@update'
]);
现在,在您的PostController中,您将收到id作为更新方法参数,并可以使用它来查找帖子和更新number_of_likes:
public function update($id)
{
$post = Post::findOrFail($id);
$post->number_of_likes++;
$post->save();
return Redirect::back();
}
创建应该来自的帖子时PostController@create您应该用零初始化numberoflikes。
最后要显示帖子有多少赞,只需在按钮前添加即可:
{{$post->number_of_likes}} <button type="submit" >Like</button>
请注意,整件事可以用很多不同的方法来完成,但这是一种基本的方法。当你做到这一点时,如果需要的话,你可以尝试用一些javascript来改进它。