【发布时间】:2021-01-03 10:04:25
【问题描述】:
我需要一些小帮助,关于我在 ProductController@store 中的 store 方法。基本上我有一个表单 createProduct.blade.php,它允许用户添加产品、名称、图像、描述和链接。 ProductController@store 然后获取表单输入数据并将其保存在数据库中。现在我的问题是数据没有保存在我的数据库中,视图没有返回到 /pr 这是我的 productManagement.blade.php 页面,运行代码时没有显示错误消息。单击提交后,当前输出只是一个空表单。我希望输出是存储到数据库中的表单输入数据,并且用户重定向到 /pr。我已经包含了一些代码,我认为这些代码应该会导致这个令人头疼的问题。
ProductController@store
public function store(Request $request)
{
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('input_img')) {
$image = $request->file('input_img');
$name = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$this->save();
}
$data = request()->validate([
'productName' => 'required',
'productLink' => 'required',
'productPrice' => 'required',
'productDescription' => 'required',
]);
$product = new Product([
'productName' => $request->get('productName'),
'productLink' => $request->get('productLink'),
'productPrice' => $request->get('productPrice'),
'productDescription' => $request->get('productDescription')
]);
$product->save();
return redirect('/pr');
}
createProduct.blade.php
<form action="/storeProduct" method="post">
@csrf
<label for="productName">Product Name:</label><br>
<input type="text" id="productName" name="productName" autocomplete="off" value="{{
old('productName') }}"><br>
@error('productName') <p style="color: red">{{ $message }}</p> @enderror
<label for="productImage">Product Image:</label><br>
<input type="file" id="productImage" name="productImage" autocomplete="off" value="{{
old('productImage') }}"><br>
@error('productImage') <p style="color: red">{{ $message }}</p> @enderror
<label for="productLink">Product Link:</label><br>
<input type="text" id="productLink" name="productLink" autocomplete="off" value="{{
old('productLink') }}"><br>
@error('productLink') <p style="color: red">{{ $message }}</p> @enderror
<label for="productPrice">Product Price:</label><br>
<input type="decimal" id="productPrice" name="productPrice" autocomplete="off" value="{{
old('productPrice') }}"><br>
@error('productPrice') <p style="color: red">{{ $message }}</p> @enderror
<label for="productDescription">Product Description:</label><br>
<input type="text" id="productDescription" name="productDescription" autocomplete="off" value="
{{ old('productDescription') }}"><br>
@error('productDescription') <p style="color: red">{{ $message }}</p>
@enderror
<input type="submit" value="Submit">
</form>
web.php
Route::post('/storeProduct', 'ProductController@store');
是的,我不知道为什么这不起作用。我从另一个 stackoverflow 问题中阅读了存储图像的解决方案,获得了 41 个赞成票,所以我不知道为什么该解决方案适用于除我之外的所有人......感谢您阅读并尝试提供帮助。
【问题讨论】:
-
你应该在那个控制器中有另一个方法叫做
save(),你能把它添加到你的问题中吗? -
你需要调整你的表单来处理上传文件
enctype='multipart/form-data'...还有什么是input_img你没有任何具有该名称的文件输入...只有productImage -
啊!从另一个 stackoverflow 问题中学习时,我忘记将 input_img 更改为 productImage ......
-
我没有一个叫做 save() 的东西...我的控制器就像一个基础资源控制器,它会生成它需要的所有方法。