In my product table I have a product_id field which is not the primary key where I want to insert category name with 3 digit unique id in that field using laravel ORM. Please help me how I can implement it
Category Table
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('description');
$table->timestamps();
});
Product Table
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('product_id');
$table->unsignedBigInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
$table->string('name', 100);
$table->float('price', 5);
$table->text('description');
$table->timestamps();
});
Product Store Method
public function store(Request $request)
{
$product = new Product();
$product->product_id = **How can I implement that? (Example: Category-321)**
$product->name = $request->name;
$product->category_id = $request->category;
$product->price = $request->price;
$product->description= $request->description;
$product->save();
return redirect()->route('product.index');
}
You can use mt_rand like -
public function store(Request $request)
{
$categoryname = $request->your-category-name;
do{
$productid = $categoryname.'-'.mt_rand(100, 999);;
}while(DB::table('products')->where('product_id', $productid)->exists());
$product = new Product();
$product->product_id = $productid;
$product->name = $request->name;
$product->category_id = $request->category;
$product->price = $request->price;
$product->description= $request->description;
$product->save();
return redirect()->route('product.index');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With