1

I have a booking app and I have a column in my table named reference_no and I want to assign it to a random string? Does anyone knows how to do it in laravel? Where should I put the code of the random string generator? In the migrations or in the controller? Thanks for the help.

Controller

public function addBooking(Request $request,$fid){

        $booking = Booking::create([
            'flight_id'=> $fid,
            'mobile_no' => $request->mobile_no,
            'email' => $request->email,
            'seat_no' =>$fid,
            'reference_no' => THIS IS THE COLUMN THAT I WANT TO HAVE A UNIQUE RANDOM STRING,
            //add if you want you add any more column
        ]);

        foreach($request->title as $key => $value){
            BookingDetails::create([
                'booking_id' => $fid,
                'title' => $request->title[$key],
                'fname' => $request->fname[$key],
                'lastname' => $request->lname[$key],
                //other columns
            ]);
        }


    }

migration

    public function up()
    {
        Schema::create('bookings', function (Blueprint $table) {
            $table->bigIncrements('booking_id');
            $table->bigInteger('flight_id')->unsigned();
            $table->string('email');
            $table->string('mobile_no');
            $table->integer('seat_no');
            $table->string('reference_no',10)->unique();
            $table->timestamps();
        });

        Schema::table('bookings', function($table) {
            $table->foreign('flight_id')
                  ->references('flight_id')->on('flights')
                  ->onDelete('cascade');
        });
    }


Model

class Booking extends Model
{
    protected $fillable = [
         'flight_id','booking_id', 'email', 'mobile_no', 'seat_no', 'reference_no',
    ];
}
draw134
  • 1,053
  • 4
  • 35
  • 84
  • 1
    i believe you can find something [here](https://stackoverflow.com/questions/4356289/php-random-string-generator) – fazrinwiraman Sep 19 '19 at 02:17
  • migration and controller has different use. you can read more in docs [migration](https://laravel.com/docs/6.x/migrations) and [controller](https://laravel.com/docs/6.x/controllers). – fazrinwiraman Sep 19 '19 at 02:26

3 Answers3

2

Laravel has a helper class named Str for dealing with strings.
https://laravel.com/docs/master/helpers

use Illuminate\Support\Str;

$random = Str::random(40);

Please note that as of Laravel 6, the str_ helper functions such as str_random() have been moved to the additional laravel/helpers package.
https://laravel.com/docs/6.x/upgrade#helpers

composer require laravel/helpers
matticustard
  • 4,850
  • 1
  • 13
  • 18
1

Define this function to helper.php file and use it.

helper.php

function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

Now you may use it. and length should be as your requirement.

$booking = Booking::create([
            'flight_id'=> $fid,
            'mobile_no' => $request->mobile_no,
            'email' => $request->email,
            'seat_no' =>$fid,
            'reference_no' => generateRandomString(8),
            //add if you want you add any more column
        ]);
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
0

I just found the solution, so I must put the random string generator code in my controller. As I figured out. Big thanks go @fazinwiraman.

 public function addBooking(Request $request,$fid){

        $booking = Booking::create([
            'flight_id'=> $fid,
            'mobile_no' => $request->mobile_no,
            'email' => $request->email,
            'seat_no' =>$fid,
            'reference_no' => str_random(10),
            //add if you want you add any more column
        ]);

        foreach($request->title as $key => $value){
            BookingDetails::create([
                'booking_id' => $fid,
                'title' => $request->title[$key],
                'fname' => $request->fname[$key],
                'lastname' => $request->lname[$key],
                //other columns
            ]);
        }


    }
draw134
  • 1,053
  • 4
  • 35
  • 84
  • better try to select the random if zero result then insert if you found result generate a new one. – Mohd Alomar Sep 19 '19 at 02:22
  • how could i do that sir? and also is there a way that i could generate a random unique string using `str_random`? – draw134 Sep 19 '19 at 02:26
  • 1
    if that reference number is for users, you should consider making it more readable and a bit easier to remember. for example only use alphabets and 8 characters. – fazrinwiraman Sep 19 '19 at 02:29
  • yes sir. actually i have an idea about it. What if i will put a static combination of letters and numbers like ABCDXYZ + the booking id then it will always increment. Is that a good idea? – draw134 Sep 19 '19 at 02:30
  • 1
    its a good idea. but do not use your database ID as suffix to your reference number. create a function to generate the reference number which contains a query to get last reference number and increment it and append the number to your prefix. – fazrinwiraman Sep 19 '19 at 02:36
  • 1
    no it is not because it will be predictable, static plus random is good. add this before $reference_no = str_random(10); $booking = Booking::where('reference_no', $reference_no)->get(); while($booking->isNotEmpty()){ $reference_no = str_random(10); $booking Booking::where('reference_no', $reference_no)->get(); } – Mohd Alomar Sep 19 '19 at 02:39