多态关联 --点赞

本文介绍了如何在 Laravel 框架中实现文章的点赞功能。通过创建迁移文件添加相关字段,建立 Article 模型的关联关系,定义 toggle 方法来控制赞与取消赞的操作,并在 Controller 中处理,同时配置路由和页面布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建迁移文件

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值