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

Viewed 358

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');
    }
2 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');
}

In

Schema::create('products', function (Blueprint $table) {

Change:

$table->unsignedBigInteger('category_id'); 

to:

$table->string('category_id');

So that category_id field can accept strings. Then change the store method as given below:

public function store(Request $request)
    {

        $category = Category::find($request->category);

        $product = new Product();
        $product->product_id = $category->name . '-321'; // you can replace 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');
    }
Related