Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert Category name with 3 digit unique id in Product table field in laravel

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');
    }
like image 678
Saimun Hossain Avatar asked Dec 05 '25 19:12

Saimun Hossain


1 Answers

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');
}
like image 140
Rashed Hasan Avatar answered Dec 08 '25 08:12

Rashed Hasan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!