我正在尝试制作一个允许登录管理员编辑产品的 Laravel 项目。编辑视图有效,但是一旦保存更改,它就会update()
在 null 错误时引发对成员函数的调用。
public function edit($id)
{
$products = Product::with(['categories'])->find($id);
$categories = Category::all();
return view('products.edit', compact('products', 'categories'));
}
public function update(Request $request, $id)
{
$product = Product::find($id);
$product->update($request->only(['name', 'description', 'weight', 'price']));
$product->categories()->sync($request->get('category_id'));
return redirect('/products');
}
但是,我收到以下错误:
在 null 上调用成员函数 update()
视图/刀片
<div style="width: 50%;position: relative;left: 20%;top: 30px;">
<form method="POST" action="{{route('products.update',['id',$products->id])}}">
@csrf
@method('PUT')
<div class="card">
<div class="card-body">
<h1 style="text-align: center">
Edit Product {{$products->name}}
</h1>
<div class="form-group" style="display: grid;background: cornsilk;">
<div class="form-group">
<label for="name">Name:</label>
<input name="name" value="{{$products->name}}" class="form-control">
</div>
<div class="form-group">
<label for="description">Description:</label>
<input name="description" value="{{$products->description}}" class="form-control">
</div>
<div class="form-group">
<label for="weight">Weight:</label>
<input name="weight" value="{{$products->weight}}" class="form-control">
</div>
<div class="form-group">
<label for="price">Price:</label>
<input name="price" value="{{$products->price}}" class="form-control">
</div>
<div class="form-group">
<label for="category">Category:</label>
<select name="category_id[]" class="form-control" multiple>
@foreach($categories as $category)
<option value="{{$category->id}}"
{{$products->categories->contains('id',$category->id) ? 'selected':''}}
>{{$category->name}}</option>
@endforeach
</select>
</div>
{!! Form::submit('submit',['class','btn btn-success']) !!}
</div>
@if ($errors->any())
<div class="alert alert-danger" style="direction: rtl;text-align: right">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
</div>
</div>
</form>
</div>