【发布时间】:2019-07-15 17:26:39
【问题描述】:
我有两个问题需要你的帮助。首先,我已经为 cmets 做了一个删除路线,但是其他登录的用户也可以从直接链接中删除 cmets...link.com/deleteComment/id。如何使其仅对评论的所有者可用?所有者 ID 保存在数据库中,可以使用{{ $comment->user_id }} 访问。
第二个问题...在我看来,当我点击一张没有 cmets 的照片时,我收到了undefined variable comment,但我不知道为什么,因为在带有 cmets 的照片上,我没有问题。可以我做了类似if comments != empty, dont show it 之类的东西?
评论控制器:
public function store(Request $request, $post_id)
{
$this->validate($request, array(
'comment' => 'required|min:5|max:2000',
));
$post = Post::find($post_id);
$comment = new Comment();
$comment->username = Auth::user()->username;
$comment->email = Auth::user()->email;
$comment->user_id = Auth::user()->id;
$comment->comment = $request->comment;
$comment->approved = true;
$comment->post()->associate($post);
$comment->save();
Session::flash('message', "Message posted successfully!");
return Redirect::back();
}
PostsController:
public function delete($id){
DB::table('posts')->where('id',$id)->delete();
return redirect('/profile/' . auth()->user()->id);
}
我的看法
@foreach($post->comments as $comment)
<div class="comment d-flex ">
<p><strong><a class="text-dark" href="/profile/{{ $comment->user_id }}">{{ $comment->username}}</a>: </strong> {{ $comment->comment}}</p>
@can('update', $post->user->profile)
<div class="dropdown col-md-6">
<button type="button" class="btn btn-primary dropdown-toggle btn-sm" style="background-color: #ffffff00;border: 1px solid #555;color: black;padding: 0 5px" data-toggle="dropdown">
Select
</button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Edit comment</a>
<a class="dropdown-item" title="Options" style="text-decoration: none;" href="/deleteComment/{{$comment->id}}">Delete comment</a>
</div>
</div>
</div>
@endcan
@endforeach
我的路线
Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']);
Route::get('/deleteComment/{id}', 'CommentsController@delete');
【问题讨论】:
-
如何使此内容仅对评论的所有者可用?使用 laravel 策略,laravel.com/docs/5.8/authorization#creating-policies
-
对于第二期,用
@if($post->comments->count() > 0)和@endif包装你的foreach -
谢谢,但是这个
@if不起作用,有什么解决办法吗? -
你有没有把
@if放在@foreach之前如果是的话,我认为问题出在$comment->comment这一行,使用{{ isset($comment->comment) ? $comment->comment : "--" }} -
是的...也许我说错了?你能看看吗? codepen.io/anon/pen/BgeXPV