php在注释 项目,php – 在Laravel项目中为注释创建Like系统时遇到问题

我正在使用Laravel创建一个项目.用户可以喜欢评论.我想显示一个“喜欢”按钮,以便用户可以喜欢评论,如果用户已经喜欢评论,我希望该按钮“不像”,这样用户可以不同于喜欢的评论

在我的数据库中,我有一个喜欢的表:

| id | user_id | comment_id |

我喜欢的模型看起来像这样:

class Like extends \Eloquent {

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

protected $table = 'likes';

public function owner()

{

return $this->belongsTo('Acme\Users\User', 'user_id');

}

}

评论模型如下所示:

class Comment extends \Eloquent {

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

protected $table = 'comments';

public function owner()

{

return $this->belongsTo('Acme\Users\User', 'user_id');

}

public function likes()

{

return $this->hasMany('Acme\Likes\Like');

}

}

用户模型:

class User extends Eloquent {

public function comments()

{

return $this->hasMany('Acme\Comments\Comment');

}

public function likes()

{

return $this->hasMany('Acme\Likes\Like');

}

}

喜欢控制器:

class LikesController extends \BaseController {

use CommanderTrait;

/**

* Like a comment

* @return Response

*/

public function commentLike()

{

// using a command bus. Basically making a post to the likes table assigning user_id and comment_id then redirect back

extract(Input::only('user_id', 'comment_id'));

$this->execute(new CommentLikeCommand($user_id, $comment_id));

return Redirect::back();

}

public function unlike()

{

$like = new Like;

$user = Auth::user();

$id = Input::only('comment_id');

$like->where('user_id', $user->id)->where('comment_id', $id)->first()->delete();

return Redirect::back();

}

}

在我看来,我可以通过$comment获得评论,我可以通过$comment->获得喜欢:喜欢:

@foreach($post->comments as $comment)

{{ $comment->owner->first_name }} {{ $comment->owner->last_name }} {{ $comment->body }}

 {{ $comment->created_at->diffForHumans() }} ·

@if ($comment->likes->owner->id === $currentUser->id)

{{ Form::open(['route' => 'like']) }}

{{ Form::hidden('user_id', $currentUser->id) }}

{{ Form::hidden('comment_id', $comment->id) }}

Like

{{ Form::close() }}

@else

{{ Form::open(['route' => 'unlike']) }}

{{ Form::hidden('user_id', $currentUser->id) }}

{{ Form::hidden('comment_id', $comment->id) }}

Unlike

{{ Form::close() }}

@endif

@endforeach

我试图设置一个if语句,以查看当前用户是否喜欢该状态,但我不知道如何做到这一点?如果用户还不喜欢评论,我想要显示“喜欢”按钮.如果用户喜欢评论,我希望显示“不同”按钮.我想我可以说@if($comment-> likes-> owner-> id === $currentUser-> id)但我得到了Undefined属性.我该怎么做呢?

解决方法:

$comment-> likes是Like对象的集合.要访问所有者属性,您需要迭代该集合.

但是,另一种选择是使用Collection上的可用方法来执行您需要的操作:

@if (in_array($currentUser->id, $comment->likes->lists('user_id')))

$comment-> likes-> lists(‘user_id’)将返回Comment的Likes集合中所有user_id值的数组. in_array()将检查$currentUser-> id是否在该数组中.

标签:php,laravel,eloquent,blade

来源: https://codeday.me/bug/20190824/1711820.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值