【发布时间】:2021-09-15 21:31:54
【问题描述】:
我正在使用 Laravel 5.8 开发我的项目,我有这张表,其中显示了数据库中的一些数据:
@foreach(\App\Shop\ProductDelivery::all() as $delivery)
<tr>
<td>{{ $delivery->name }}</td>
<td>{{ $delivery->price }}</td>
<td>
<a href="{{ route('editFreeDelivery', $delivery->id) }}">Edit</a>
</td>
</tr>
@endforeach
如您所见,有一个名为Edit 的链接用于编辑这些数据,因此当有人点击该链接时,此方法会运行:
Route::get('product-information-pages/free-deliveries/{productDelivery}/edit', 'ShopInformationPagesAdminController@editFreeDelivery')->name('editFreeDelivery')->middleware('permission:static-page-manage');
public function editFreeDelivery(ProductDelivery $productDelivery)
{
return view('admin.shop.deliveries.edit', compact('productDelivery'));
}
我还添加了这个表格来更新发送到edit.blade.php的数据:
<form action="{{ route('updateProductDelivery', [$productDelivery->id]) }}" method="POST" enctype="multipart/form-data">
@csrf
{{ @method_field('PATCH') }}
<label for="title" class="control-label">Name</label>
<input type="text" id="title-shop" name="name" disabled="disabled" class="form-control" value="{{ old('name' , $productDelivery->name) }}" autofocus>
<label for="price" class="control-label">Price</label>
<input type="text" id="price_shop" name="price" class="form-control" value="{{ old('price' , $productDelivery->price) }}" autofocus>
<button class="btn btn-success" type="submit">Submit</button>
</form>
这里是更新数据的方法:
Route::patch('product-information-pages/free-deliveries/{productDelivery}', 'ShopInformationPagesAdminController@updateProductDelivery')->name('updateProductDelivery')->middleware('permission:static-page-manage');
public function updateProductDelivery(Request $request, ProductDelivery $productDelivery)
{
try {
$data = $request->validate([
'name' => ['required'],
'price' => ['required','integer'],
]);
$productDelivery->update($data);
} catch (\Exception $e) {
dd($e);
}
return redirect(route('product-information-pages.create'));
}
但现在的问题是,数据不会以某种方式更改和更新,而是显示为dd($e):
那么这里出了什么问题?我该如何解决这个问题?
最后是模型ProductDelivery.php:
class ProductDelivery extends Model
{
protected $table = "product_deliveries";
}
而表product_deliveries 看起来像这样:
更新 #1:
dd($productDelivery->toArray()); 的结果如下:
array:5 [▼
"id" => 1
"name" => "Free Delivery"
"price" => 300000
"created_at" => "2021-07-04 14:16:09"
"updated_at" => "2021-07-04 14:16:09"
]
【问题讨论】:
-
updateProductDelivery 没有更新数据库的代码。它只有验证码
-
@JohnLobo 我已经添加了
$productDelivery->update($data);,但仍然没有更新数据并显示#message: "The given data was invalid." -
添加受保护的 $guarded = ['id'];在你的模型中
-
@JohnLobo 我做了但仍然没有更新数据并显示消息
-
@JohnLobo 我也加了
protected $fillable = ['price', 'name'];,但没有解决问题!
标签: php laravel eloquent laravel-5.8