how to generate unique number in laravel

How to generate unique Order numbers in Laravel ?

In this article, we will learn How to Generate Unique Order numbers in Laravel,
Unique Order number mostly used to manage Products, Orders, or Invoice for identifying a particular product, order, or invoice.

Let’s Start from Scratch :

I’m going to show you about Generate Unique Number in laravel,
you can use this given logic in laravel 5.8, laravel 6, laravel 7, and laravel 8 frameworks.

Generating Migrations

At first, we create a new migration file for “products”, In your cmd terminal hit the given below command

php artisan make:migration create_products_table

Migration Structure

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('product_no');
            $table->string('name');
            $table->string('description');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Running Migrations

After defining columns and data types For migrating in the cmd terminal hit the given below command.

php artisan migrate
how to generate unique number in laravel

Create Model

In your cmd terminal hit the given below command,

php artisan make:model Product

Here, we define our table, and fillable all the Columns,

App/Product

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';
    protected $fillable = ['id','product_no','name','description'];
}

Create Controller

Let’s create a controller, in cmd terminal hit the given below command


php artisan make:controller ProductController

Define Routes

routes/web.php

In the web.php file, we define our routes for Add, Store, and List of Products.

Route::get('/add-product','ProductController@addProduct')->name('add.product');
Route::post('/store-product','ProductController@storeProduct')->name('store.product');
Route::get('/list-product','ProductController@ListProduct')->name('list.product');

Functionality & Logic

App\Http\Controllers\ProductController

In the ProductController we write Logic for storing the parameters and generate unique numbers for our products.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    public function addProduct(){
     return view('product.add');
    }

    public function storeProduct(Request $request){
     $product = new Product();
     $product->name = $request->product_name;
     $product->description = $request->product_desc;
     
     #Store Unique Order/Product Number
     $unique_no = Product::orderBy('id', 'DESC')->pluck('id')->first();
        if($unique_no == null or $unique_no == ""){
        #If Table is Empty
        $unique_no = 1;
        }
        else{
        #If Table has Already some Data
        $unique_no = $unique_no + 1;
      }
     $product->product_no = 'PROD'.$unique_no;
     $product->save();
     return redirect()->route('list.product');
    }

    public function ListProduct(){
      $productList = Product::get();
      return view('product.list',compact('productList'));
    }
}

Create Blade Files

In the resources/views directory, we create product folder, under product folder we create 2 blade files.

  1. add.blade.php 2. list.blade.php

If you want to write validation rules for add.blade.php file for required fields foloow this article :

Easy Form Validation With j-query

resources/views/product/add.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>How to store unique order number</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
        <br>
         <h3>Laravel - Generate unique Order | Product no</h3>
         <a class="btn btn-primary" href="{{route('list.product')}}" role="button">Product List</a>
         <br>
         <br>
         <div class="card">
            <form method="post" action="{{route('store.product')}}">
               @csrf
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Product Name">Product Name :</label>
                        <input type="text" class="form-control" placeholder="Enter Product name" name="product_name" required>
                     </div>
                     <div class="col-md-6">
                        <label for="Product Description">Product Description :</label>
                        <input type="text" class="form-control" placeholder="Enter Product description" name="product_desc" required>
                     </div>
                  </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
               <br/>
         </div>
         </form>
      </div>
   </body>
</html>
how to generate unique number in laravel

resources/views/product/list.blade.php

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Product List Data</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
         <h3>Product List Data</h3>
         <a class="btn btn-primary" href="{{route('add.product')}}" role="button">Add Product</a>
         <table class="table">
            <thead>
               <tr>
                  <th>S.no</th>
                  <th>Order / Product No.
                  <th>Product Name</th>
                  <th>Product Description</th>
               </tr>
            </thead>
            <tbody>
               @foreach($productList as $key => $data)
               <tr>
                  <td>{{ $key+1 }}</td>
                  <td>{{$data->product_no}}</td>
                  <td>{{$data->name}}</td>
                  <td>{{$data->description}}</td>
               </tr>
            </tbody>
            @endforeach
         </table>
      </div>
   </body>
</html>
how to generate unique number in laravel
how to generate unique number in laravel

NOTE: You can use this logic to generate unique numbers for product, orders, or Invoices.

Final Words

In this article, we learned “How to generate unique Order numbers in Laravel”, I hope this article will help you with your Laravel application Project.

Real Also : How to Insert Data using Ajax in Laravel ?

1 thought on “How to generate unique Order numbers in Laravel ?”

Comments are closed.