I have this migration:
class CreatePendingCredits extends Migration
{
public function up()
{
Schema::create('pending_credits', function (Blueprint $table) {
$table->id();
$table->uuid('uuid')->unique()->default(DB::raw('UUID()'));
$table->foreignIdFor(App\Models\User::class, 'user_id')->references('id')->on('users');
$table->double('amount');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('pending_credits');
}
}
When I'm creating a new record for pending_credits, I don't set uuid attribute, so database will generate a new uuid (uses the default value).
Let's say for some reason I need to update the uuid of one record just like when I'm creating a new record and database generates the uuid.
Is it:
PendingCredit::find(18)->update(['uuid'=>null]);
Or:
PendingCredit::find(18)->update(['uuid'=>DB::raw('UUID()')]);
Or is there a standard way to this?
Update
Imagine the default value is not just a simple UUID() in your database, then it's not good to copy your default expression from database into your code.
Try with this:
$table->double('amount')->default(1);
Related
I have a multi-tenant installation and am working with creating new hosts automatically. I am trying to simply set the Allow Null value on a table for each of the columns when the table is first created. This is not working but later migration files that add new columns to the existing table to work with setting them to nullable.
I am using the following to first create the table, null not set:
public function up()
{
Schema::create('phone_logs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('type')->nullable(true)->change();
$table->string('groupId')->nullable(true)->change();
$table->string('status')->nullable(true)->change();
$table->string('status_code')->nullable(true)->change();
$table->longText('message')->nullable(true)->change();
$table->string('sender')->nullable(true)->change();
$table->string('receiver')->nullable(true)->change();
$table->string('contactNumber')->nullable(true)->change();
$table->dateTime('date')->nullable(true)->change();
$table->string('messageUID')->nullable(true)->change();
$table->integer('has_read')->nullable(true)->change();
$table->string('lists_sent')->nullable(true)->change();
$table->string('user_id')->nullable(true)->change();
$table->string('audio')->nullable(true)->change();
$table->timestamps();
});
}
Then using this to add 3 new columns to the table and it does set null:
public function up()
{
Schema::table('phone_logs', function (Blueprint $table) {
//
$table->string('reply_numbers')->nullable(true);
$table->text('auto_response_1')->nullable(true);
$table->dateTime('schedule_date')->nullable(true);
});
}
I added ->change() after reading a few suggestions and also included nullable(true) instead of just nullable() as that was suggested as well but still doesn't set and requires me to do so manually.
Let's say I have 4 tables in my database, and I want to only drop this table using a migration.
2019_11_27_093224_create_objects_table.php*\
class CreateObjectsTable extends Migration
{
public function up()
{
Schema::create('objects', function (Blueprint $table) {
$table->bigIncrements('id_object', 'KO0');
$table->string('nama_layanan');
$table->string('tipe_object');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('objects');
}
}
Can I drop this table alone or do I need to wipe out all of my tables in my database?
Best way to do that just use phpmyadmin and drop the table manually. Of course if the migration is still there when you run the migration again the table will be created again.
If you do not want to re-create/migrate the table, just remove in under /database/migrations
That is very easy. You just create a new migration to turn around above migration
php artisan make:migration drop_objects_table.
class DropObjectsTable extends Migration
{
public function up()
{
Schema::dropIfExists('objects');
}
public function down()
{
Schema::create('objects', function (Blueprint $table) {
$table->bigIncrements('id_object', 'KO0');
$table->string('nama_layanan');
$table->string('tipe_object');
$table->timestamps();
});
}
}
Laravel supports create a migrations table in your database, in this table has id, migration_name, step of migrating when you run command. You can rollback 1 or many step in migrations table. You can read in doc
I would like to add a custom prefix to UUIDs within Laravel to help keep better track of Database entries. Currently, when called, the uuid(); function will produce a table entry like this:
6ab4a8c-9597-lle7-a63c-0242c100426l
But I would like to be able to a a prefix infront of every uuid entry within that table. For instance, Users within the Users table would have a uuid prefixed with UUID of:
UUID-6ab4a8c-9597-lle7-a63c-0242c100426l
and Posts would be saved in the Posts table with a PUID prefix:
PUID-6ab4a8c-9597-lle7-a63c-0242c100426l
to signify ('Post' Unique Identifier).
The default migration for the Users table is as follows:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
To use UUIDs, the following would be used:
Schema::create('users', function (Blueprint $table) {
$table->uuid('uuid')->primary();
});
I'm not sure where the models defining UUID(s) are stored, and I'm not sure I'd want to modify the entire model.
Ideally, the a uuid would be defined using the table name, then the prefix as such:
$table->uuid('puid', 'PUID')->primary();
Does anyone know how this could be implemented?
Thanks in advance.
You can use an accessor and a mutator to achieve what you want in your frontend, but the database will contain an UUID formatted value, because it's an UUID column.
In your Users model:
public function getUuidAttribute($value)
{
return "UUID-".$value;
}
public function setUuidAttribute($value)
{
$this->attributes['uuid'] = str_replace("UUID-", "", $value);
}
and in your Posts Model:
public function getPuidAttribute($value)
{
return "PUID-".$value;
}
public function setPuidAttribute($value)
{
$this->attributes['puid'] = str_replace("PUID-", "", $value);
}
you will see UUID-6ab4a8c-9597-lle7-a63c-0242c100426l when you dump $user->uuid and same will happen with $post->puid with a prefix of PUID-.
Otherwise, you should generate your UUID's yourself, and save them as a string in the database.
I would like to add an un-nullable column to an existing table with some rows in Laravel migration.
In SQL, I understand such an action should be performed inside a transaction in the order of
adding a column
initialising the column
making it un-nullable
so as to guarantee
the initialisation to be performed without disrupting the DB integrity, and
ALTER TABLE not to violate the NOT NULL constraint,
The following is an example PostgreSQL code (assuming users table has a column old_col), referring to an answer:
BEGIN TRANSACTION;
ALTER TABLE users ADD COLUMN new_col integer;
UPDATE users SET new_col = old_col + 1;
ALTER TABLE users ALTER COLUMN new_col SET NOT NULL;
COMMIT;
An ordinary Laravel migration file like this would not work.
public function up()
{
Schema::table('users', function($table) {
$table->integer('new_col'); // ->nullable(false) // later?
});
}
How can one implement a SQL transaction or its equivalent in Laravel migration?
NOTE (edited):
If you want to set up the default value, and if you do not need to (absolutely simultaneously) update the column for the existing rows as a function of some values of each row, then you can simply specify ->default(0) or something like that in the migration file (and avoid all the tricks!). My intention of the question was not to set up the default for the column to add.
The solution with three queries:
DB::transaction(function () {
Schema::table('users', function (Blueprint $table) {
$table->integer('id_cloned')->nullable();
});
App\Models\User::query()->update([
'id_cloned' => DB::raw('id + 1'),
'updated_at' => DB::raw('now()') // if you want to touch the timestamp
]);
Schema::table('users', function (Blueprint $table) {
$table->integer('id_cloned')->nullable(false)->change();
});
});
Alternative solution without DB::raw parts, but will generate separate update query for every record:
DB::transaction(function () {
Schema::table('users', function (Blueprint $table) {
$table->integer('id_cloned')->nullable();
});
foreach (App\Models\User::all() as $row) {
$row->id_cloned = $row->id + 1;
$row->save();
}
Schema::table('users', function (Blueprint $table) {
$table->integer('id_cloned')->nullable(false)->change();
});
});
You need to set default value to whatever you want:
public function up()
{
Schema::table('users', function($table) {
$table->integer('new_col')->default(0);
});
}
you can your code in foreach like $methodName = 'item->get'.$method.'()';
class Item {
getFoo();...
getBar();...
}
$methods = ['Foo','Bar'];
foreach($methods as $method){
$methodName = 'item->get'.$method.'()';
echo $methodName;
}
i have 9 tables, when i run command :
php artisan migrate
only users table, migration table and password_reset table are created in my database. this is my sample code
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAlatsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('alats', function (Blueprint $table) {
$table->increments('id');
$table->integer('merk_id')->unsigned();
$table->integer('kategori_id')->unsigned();
$table->integer('operator_id')->unsigned();
$table->string('nama');
$table->string('no_plat',15);
$table->date('tahun');
$table->string('volume',20);
$table->text('keterangan');
$table->enum('status',['ada','disewa','servis']);
// $table->timestamp('created_at');
// $table->timestamp('updated_at');
$table->timestamps();
$table->foreign('merk_id')->references('id')->on('merks')->onDelete('CASCADE');
$table->foreign('kategori_id')->references('id')->on('kategoris')->onDelete('CASCADE');
$table->foreign('operator_id')->references('id')->on('operators')->onDelete('CASCADE');
});
}
public function down()
{
Schema::dropIfExists('alats');
}
}
please help me..?
The migration files need to be migrated in right order. You can't migrate a table with a non existing foreign key.
You probably have a foreign key in some migration and the id key for that will come to existence later in the next migration file. That is why you get this error.
Check your migration files and watch out on order they get created.
For example if you have a foreign key alats_merk_id_foreign then the migration file with alats_merk_id must be migrated before.
Schema::create('alats', function (Blueprint $table) {
$table->increments('id');
$table->integer('merk_id')->unsigned();
});
Schema::table('alats', function(Blueprint $table)
{
$table->foreign('merk_id')
->references('merk_id')->on('merk_id_table_name')
->onDelete('cascade');
});
First create only table and then create foreign key.
And make sure merk_id_table should migrate first.
if you did every thing in all answers
I think your problem is from the foreign/primary key type and length
so you may create the id as integer and its corresponding foreign key as an integer with different length, or even as another type as string forexample
so try to make integers with unsigned and same length
try to use ->unsigned()->length(10)...
solution:
to make the pimary key and its corresponding foreign key in the same exact type and length
Try doing it like this:
Schema::disableForeignKeyConstraints();
Schema::create('alats', function (Blueprint $table) {
$table->increments('id');
$table->integer('merk_id')->unsigned();
$table->integer('kategori_id')->unsigned();
$table->integer('operator_id')->unsigned();
$table->string('nama');
$table->string('no_plat',15);
$table->date('tahun');
$table->string('volume',20);
$table->text('keterangan');
$table->enum('status',['ada','disewa','servis']);
// $table->timestamp('created_at');
// $table->timestamp('updated_at');
$table->timestamps();
$table->foreign('merk_id')->references('id')->on('merks')->onDelete('CASCADE');
$table->foreign('kategori_id')->references('id')->on('kategoris')->onDelete('CASCADE');
$table->foreign('operator_id')->references('id')->on('operators')->onDelete('CASCADE');
});
Schema::enableForeignKeyConstraints();
You need to replicate the above for every migration.