Schema::table
is only to update you Database table, without using to coresponding SQL statments. In SQL there is no column type that automatically fills your table with a random string. Therefor the column type hast to be string
.
See all types that exit in Laravel 5.5 https://laravel.com/docs/5.5/migrations#columns
$table->string('key', 5);
The next question is if the key
must be unique, if so then you can append the unique() function:
$table->string('key', 5)->unique();
If you have already data than you have to to this in a secound step, after, you fild in all your keys.
You have two options to fill random data in your column, with PHP (Laravel) or with SQL. With SQL you have to write a function and the function can be different depending on your SQL Server Type e.g.: Default random 10 character string value for SQL Server column
With Laravel Eloqent you don't have to think about what SQL Server you have.
$threads = new Threads();
$threads->key = str_random(5);
$threads->save();
If you used the ->unique()
function this could throw an exception if your APP create a key twice. Then you have to catch the Exception and try it again.
/* only if you need a unique Key */
$threads = new Threads();
while (true)
{
try
{
$threads->key = str_random(5);
$threads->save();
// We could save now we break out of the loop
break;
}
catch (Exception $e)
{
// Could not save, try it again
}
}
For you existing rows you can change the migration as follows:
public function up()
{
Schema::table('threads', function (Blueprint $table)
{
$table->string('key', 5);
});
$existing_threads = Threads::where('key', '')->get();
foreach($existing_threads as $threads)
{
$threads->key = str_random(5);
$threads->save();
}
}
The Model Threads
must exit before you do the migration