我在网上搜索了很长时间,并尝试将 protected $table = "brands";
添加到我的品牌模型中,如下所示:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Brand extends Model
{
protected $table = "brands";
use HasFactory;
protected $fillable = [
'brand_name',
'brand_image'
];
}
然后在我的控制器上我有以下代码:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Brand;
use Illuminate\Support\Carbon;
class BrandController extends Controller
{
public function AllBrand(){
$brands = Brand::latest()->paginate(2);
return view('admin.brand.index', compact('brands'));
}
public function StoreBrand(Request $request){
$validatedData = $request->validate([
'brand_name' => 'required|unique:brand|min:4',
'brand_image' => 'required|mimes:jpg,jpeg,png',
],
[
'brand_name.required' => 'Please input brand name',
'brand_image.min' => 'Brand longer than 4 Characters'
]);
$brand_image = $request->file('brand_image');
$name_gen = hexdec(uniqid());
$img_ext = strtolower($brand_image->getClientOriginalExtension());
$img_name = $name_gen.'.'.$img_ext;
$upload_location = 'images/brand/';
$publish_image = $upload_location.$img_name;
$brand_image->move($upload_location,$img_name);
Brand::insert([
'brand_name' => $request->brand_name,
'brand_image' => $publish_image,
'created_at' => Carbon::now()
]);
return Redirect()->back()->with('success', 'Brand added successfully!');
}
}
通过我的路线传递这个:
// For Brand Route
Route::get('/brand/all', [BrandController::class, 'AllBrand'])->name('all.brand');
Route::post('/brand/add', [BrandController::class, 'StoreBrand'])->name('store.brand');
我也在 views/admin/brand folder
中的表单中使用过:
<form action="{{ route('store.brand') }}" method="POST" enctype="multipart/form-data">
@csrf
<input type="text" name="brand_name" placeholder="Brand name"/>
@error('brand_name')
<span style="color: red; font-weight: bold;"> {{ $message }}</span>
@enderror
我的数据库表名为 brands
,但添加 protected $table = "brands";
并没有解决这个问题。我什至尝试重新迁移并重新执行此操作,但似乎没有任何效果。
还有其他方法可以解决这个问题吗?每当我添加新品牌时,我总是收到 SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel8.brand' doesn't exist (SQL: select count(*) as aggregate from
brandwhere
brand_name = Bx LLC)
错误。
请帮忙!
答案 0 :(得分:3)
问题不在于存储品牌,而在于验证:
在您的验证中:
'brand_name' => 'required|unique:brand|min:4',
这告诉 Laravel 在 'brand' 表中确保品牌名称的唯一性,因此当查询提交时,您会看到该错误。
这个验证应该是:
'brand_name' => 'required|unique:brands|min:4',
答案 1 :(得分:1)
您可以指定用于确定表名的 Eloquent 模型,而不是直接指定表名:
'brand_name' => 'required|unique:App\Models\Brand|min:4',