Laravel 5 - Set fields to nullable on table create - php

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.

Related

Laravel - Set default value of column on record update

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);

How should i create a third table for new Categories in Laravel

I'm developing a practice project where I have 2 tables. An article table with heading and text and a user table. Now I want an admin (which I created in the database before) to create additional Article Categories. Does anyone have an idea how I can link my tables or my models now ? I've only been working with Laravel for a week now and don't quite look through it yet.
That are my tables :
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('heading',80);
$table->string('clubchoose')->default('DEFAULT');
$table->text('text');
$table->timestamps();
$table->unsignedInteger('author')->nullable();
$table->foreign('author')->references('id')->on('users');
$table->string('image')->nullable();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->Increments('id');
$table->boolean('isAdmin')->default(false);
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
So in order to achieve that, you first need to create your categories model/controller/table:
php artisan make:model Category -m //-m flag creates migration automatically
php artisan make:controller CategoryController --reosource //--resource flag creates a CRUD controller.
After that, inside your categories table, add column article_id (and other fields you want):
public function up()
{
Schema::table('categories', function (Blueprint $table) {
// ...
$table->integer('article_id')->nullable();
});
}
After that, you need to alter your articles table by adding category_id column. To do that, create a new migration to add that just one column:
php artisan make:migration add_category_id_to_articles_table --table==articles
Inside that migration, add this:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->integer('category_id')->nullable();
});
}
Now that you have migrations set up, you need to set up relations. Inside your Article model, add this relation:
public function category(){
return $this->belongsTo('App\Category');
}
So an article will belong to category. For the categories, as they will have more than one article, add this relation:
public function articles(){
return $this->hasMany('App\Article');
}
So now, you have everything set up. Run migrations, and add some categories and test things out. Let me know if you have any errors or troubles.
EDIT:
If you want only an admin to add new categories, you could create a button that is only visible for admins. Something like this:
#if(Auth->user()->role == 'admin'){
//show button
#endif

Is there a way to create a custom UUID prefix for Laravel 5.8?

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.

Laravel migrate - column type string doesn't update size

I created a migration to update the size of a VARCHAR column in MySQL and to rename it in the same migration. So to change a VARCHAR() type through Laravel Schema we use string() base on Laravel docs
This is the function up():
Schema::table('address', function (Blueprint $table) {
$table->string('place_id', 100)->change();
$table->renameColumn('place_id', 'full_address');
});
and the function down():
Schema::table('address', function (Blueprint $table) {
$table->string('full_address', 255)->change();
$table->renameColumn('full_address', 'place_id');
});
It is renaming the column but it is not changing the size, any ideas why?.
MySQL table
Field, table, Type, Character Set, Display Size
place_id,address,VARCHAR,utf8,255
Thank you in advance.
I found a solution, I am not sure if it's the best one, but it is better to use multiple Schemas.
Schema::table('address', function (Blueprint $table) {
$table->string('place_id', 100)->change();
});
Schema::table('address', function (Blueprint $table) {
$table->renameColumn('place_id', 'full_address');
});

Migration laravel 5.5 : cannot create table except users table and password_reset table

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.

Categories