我希望用户只能执行诸如删除和更新自己的帖子(在本例中为评论)之类的操作。
我有两个问题要解决:
-
来自不同用户的多条评论显示在同一页上,我在每条评论旁边都有更新或删除的链接。我只希望链接出现在评论旁边,如果这是他们创建的评论。
-
我已经有了创建、更新和删除工作的功能(尽管更新和删除目前没有考虑用户是谁)。我不知道我是否需要实施门户、政策或两者兼而有之,以及这将如何影响我已经创建的内容。。。例如,我必须将控制器函数中的代码移动到策略中吗?我已经查看了Laravel资源,这对我有所帮助,但我仍然不清楚。
类具有定义的关系,例如:
class User extends Authenticatable
{
public function comments()
{
return $this->hasMany(Comment::class);
}
我有在控制器中执行操作的功能,例如:
public function addComment(Request $request, $id)
{
$request->validate([
'body' => 'required',
]);
$entry = new Comment();
$film = Film::find($id);
$entry->body = $request->body;
$entry->film_id = $film->id;
$entry->user_id = auth()->user()->id;
$entry->save();
return redirect('/');
}
public function updateComment(Request $request)
{
$request->validate([
'body' => 'required',
]);
$entry = Comment::find($id);
$entry->body = $request->body;
$entry->save();
}
注释表:
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('film_id');
$table->string('body');
$table->timestamps();
评论刀片:
<h1>{{ $film->title }}</h1>
<!--<p>{{$film->comments}}</p>-->
<table id="myTable">
<tr>
<th>Comment</th>
<th>User</th>
@if (Auth::check())
<th>Update</th>
<th>Delete</th>
@endif
@foreach ($film->comments as $comment)
<tr>
<td>{{$comment->body}}</td>
<td>{{$comment->user['name']}}</td>
@if (Auth::check())
<td><a href="/update/{{$comment->id}}">Update</a></td>
<td><a href="/delete/{{$comment->id}}">Delete</a></td>
@endif
</tr>
@endforeach
</table>
@if (Auth::check())
<div>@include('form')</div>
@else
<h3>Please log in to add a comment</h3>
@endif
@endsection
路线示例:
Route::get('/update/{id}', 'FilmsController@editComment')->name('editComment')->middleware('auth');
我目前正在使用
@if (Auth::check())
如果未登录,则隐藏链接,但这不是解决我的问题的合适方法。