创建迁移文件
php artisan make:migration --create=zans create_zans_table
在迁移文件里添加以下字段
$table->unsignedInteger ('user_id')->index()->comment('点赞用户id');
$table->unsignedInteger ('zan_id')->index()->comment('点赞的文章/视频..id');
$table->string ('zan_type')->index()->comment('点赞类型:article/comment/video...');
迁移生成表zans
php artisan migrate
在Article模型里建立关联关系
//获得所有点赞用户
public function zan ()
{
//morphToMany是模型关联中多态关联的方法
return $this->morphToMany ( User::class , 'zan' );
}
toggle方法控制赞和取消赞在ArticleController里
//<!--命名空间-->
namespace App\Http\Controllers\Home;
public function zan ( Article $article )
{
$article->zan ()->toggle ( auth ()->id () );
return back ()->with ( 'success' , '操作成功' );
}
配置路由
//{article}当前被点赞文章的信息
Route::get ( '/article/zan/{article}' , 'ArticleController@zan' )->name ( 'article.zan' );
页面布局
@if($article->zans()->get()->contains(auth()->id()))
<a href="{{route('home.article.zans',$article)}}">
<button class="btn btn-info">
<span class="fe fe-thumbs-up ">
</span>
取消点赞
</button>
</a>
@else
<a href="{{route('home.article.zans',$article)}}">
<button class="btn btn-info">
<span class="fe fe-thumbs-up ">
</span>
点个赞呗
</button>
</a>
@endif