【发布时间】:2018-01-16 01:08:14
【问题描述】:
我希望用户只能执行删除和更新他们自己的帖子(在本例中为 cmets)等操作。
我有两个问题要解决:
来自不同用户的多个 cmets 显示在同一页面上,我在每条评论旁边都有要更新或删除的链接。如果是他们创建的评论,我只希望链接显示在 cmets 旁边。
我已经拥有创建、更新和删除工作的功能(尽管更新和删除当前不考虑用户是谁)。我不知道我是否需要实施 Gates、Policies 或两者兼而有之,以及这将如何影响我已经创建的内容......例如,我是否必须将控制器函数中的代码移动到 Policy 中?我查看了有帮助的 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()) 隐藏链接,但这不适合我的问题。
【问题讨论】:
-
请把相关刀片代码也贴出来。
-
刚刚添加刀片
标签: laravel authentication crud