I’ve been searching the web for quite a long time and I have tried adding the protected $table = "brands";
to my Brand Model as seen here:
<?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Brand extends Model { protected $table = "brands"; use HasFactory; protected $fillable = [ 'brand_name', 'brand_image' ]; }
Then on my controller I have the following code:
<?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppModelsBrand; use IlluminateSupportCarbon; 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!'); } }
Passing this through my routes:
// For Brand Route Route::get('/brand/all', [BrandController::class, 'AllBrand'])->name('all.brand'); Route::post('/brand/add', [BrandController::class, 'StoreBrand'])->name('store.brand');
Which I also used on my form inside 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
My database table is named brands
but adding protected $table = "brands";
did not solve this. I even tried to re-migrate and do this all over again but nothing seems to work at all.
Are there anymore ways to solve this issue? I keep on getting the 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)
error whenever I am adding a new brand.
Please help!
Advertisement
Answer
the problem is not in storing Brand, but in validation:
in your validation:
'brand_name' => 'required|unique:brand|min:4',
this told Laravel to make sure of brand name uniqueness in ‘brand’ table, so when the query committed, you see that error.
this validation should be:
'brand_name' => 'required|unique:brands|min:4',