How to Generate UUID in Laravel?
Aug 05, 2022 . Admin
Hello Dev,
This article will provide some of the most important example how to use uuid in laravel example. it's simple example of how to generate uuid in laravel. This tutorial will give you simple example of how to generate unique id in laravel. We will use generate uuid example with laravel.
I am trying to generate a UUID laravel-uuid package. In this post we will use webpatser/laravel-uuid composer package for generate uuid in laravel. UUID stand for universally unique identifier and is a 128-bit number used to identify information in computer. I will use composer package for generate unique uuid.
You can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.
Download LaravelLet us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.
composer create-project laravel/laravel example-appGenerate Uuid in Controller File: Example 1 :
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Str; class StrController extends Controller { /** * Write code on Method * * @return response() */ public function index() { $uuid = Str::uuid(); dd($uuid); } }Example 2 :
in this step we genarate uuid using toString() function
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Str; class StrController extends Controller { /** * Write code on Method * * @return response() */ public function index() { $uuid = Str::uuid()->toString(); dd($uuid); } }Example 3 :
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Str; class StrController extends Controller { /** * Write code on Method * * @return response() */ public function index() { $uuid = (string) Str::uuid(); dd($uuid); } }Example 4 :
In this Step, We Will see how to check UUID
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Support\Str; class StrController extends Controller { /** * Write code on Method * * @return response() */ public function index() { $isUuid = Str::isUuid('a0a2a2d2-0b87-4a18-83f2-2529882be2de'); dd($uuid); } }Output :
trueExample 5 :
In this step we will see how to generate UUID in route File
Install webpatser/laravel-uuid Package:composer require webpatser/laravel-uuidweb.php
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('uuid-gen', function () { dd(Uuid::generate()->string); });
now it works...
I hope it can help you...