How to Generate Unique Random Number and String in Laravel

Hello Artisan in this quick example i will show you how you can generate unique random number and string in Laravel application. We need unique number or unique string for our application sometimes. Like when you create a ecommerce website we need a unique sq number or unique product number.

So in this example we will see several string helper that way we can use it easily like str_limit, str_plural, str_finish, str_singular etc. If we need to generate unique random string then you can use str_random() helper of Laravel. It is very simple and we can use easily.

See the below example to create a random string in Laravel:

namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use Illuminate\Support\Str;
  
class RandomController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function index()
    {
        $randomString = Str::random(30);
        dd($randomString);
    }
}

 

In this laravel generate unique code example, i will give you two example where you can generate 4, 6, 8, 10 digit random number in laravel and your php based application. From this example you can learn how to generate random unique number in laravel.

Let's see the below example of generate unique random number of Laravel:

namespace App\Http\Controllers;
  
use App\Models\Product;
  
class UniqueNumberGenerateController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $input = [
            'name' => 'Mango',
            'price' => 100,
            'code' => $this->generateUniqueNumber()
        ];
  
        $product = Product::create($input);
  
        dd($product);
    }
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function generateUniqueNumber()
    {
        do {
            $code = random_int(100000, 999999);
        } while (Product::where("code", "=", $code)->first());
  
        return $code;
    }
}

 

Read also : Some Artisan Commands to Speed Up Laravel Application

 

Hope it can help you to generate unique number and string in your php Laravel application.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.