<?php

use Illuminate\Support\Facades\Route;

Route::get('/update', function () { 
    $users = DB::table('users')->get();
    foreach ($users as $user) {
        $token = generateUniqueCode('users','api_token');
        DB::table('users')
            ->where('id', $user->id)
            ->update(['api_token' => $token]);
    }
    echo 'Update is OK.';
});

function generateUniqueCode($dbTable, $dbColumn)
{

    $characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersNumber = strlen($characters);
    $codeLength = 4;

    $userToken = [];

    for ($i = 0; $i <= 3; $i++) {
        $code = '';
        while (strlen($code) < $codeLength) {
            $position = rand(0, $charactersNumber - 1);
            $character = $characters[$position];
            $code = $code.$character;
        }
        $userToken[$i] = $code;
    }

    $userToken = implode('-', $userToken);

    if (DB::table($dbTable)->where($dbColumn, $userToken)->exists()) {
        return generateUniqueCode('users','api_token');
    }

    return $userToken;
}