我正在尝试制作允许登录用户编辑其纪念页之一的Laravel应用程序。编辑视图有效,但是一旦保存更改,就会在null错误时引发对成员函数update()的调用。我是Laravel的新手,所以如果这是一个愚蠢的问题,我深表歉意。
控制器:
public function edit(Memorial $memorial)
{
$this->authorize('update', $memorial);
return view('memorials.edit', compact('memorial'));
}
public function update(Memorial $memorial)
{
$this->authorize('update', $memorial);
$data = request()->validate([
'fname' => 'required',
'lname' => 'required',
'bio' => '',
]);
auth()->user()->memorial->update($data);
return redirect("/memorial/{$memorial->id}");
}
视图:
<div class="container pt-5">
<form action="/memorial/{{ $memorial->id }}" enctype="multipart/form-data" method="POST">
<legend>Edit Memorial</legend>
@csrf
@method('PATCH')
<div class="form-group">
<div class="form-row">
<div class="col-6">
<input id="fname" type="text" class="form-control @error('fname') is-invalid @enderror" name="fname" placeholder="First Name" value="{{ old('fname') ?? $memorial->fname }}" autofocus>
@error('fname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
<div class="col-6">
<input id="lname" type="text" class="form-control @error('lname') is-invalid @enderror" name="lname" placeholder="Last Name" value="{{ old('lname') ?? $memorial->lname }}">
@error('lname')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-6">
<input id="bio" type="text" class="form-control @error('bio') is-invalid @enderror" name="bio" placeholder="Biography" value="{{ old('bio') ?? $memorial->bio }}">
@error('bio')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-12">
<button class="btn btn-primary">Save</button>
</div>
</div>
</div>
</form>
政策:
/**
* Determine whether the user can update the memorial.
*
* @param \App\User $user
* @param \App\Memorial $memorial
* @return mixed
*/
public function update(User $user, Memorial $memorial)
{
return $user->id == $memorial->user_id;
}
您的关系不正确...您在用户模型中没有纪念性关系。所以它返回null
您可以按照以下代码轻松编辑一个纪念馆:
public function update(Memorial $memorial)
{
$this->authorize('update', $memorial);
$data = request()->validate([
'fname' => 'required',
'lname' => 'required',
'bio' => '',
]);
$memorial->update($data);
return redirect("/memorial/{$memorial->id}");
}
因为在编辑$ memorial时需要在授权中检查隐私,所以您需要
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句