Change column type to tinyInteger - php

Trying to change data column type to tinyInteger in a Laravel 5.2 migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTableNameTableChangeNotificationSentTinyint extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('table_name', function ($table) {
$table->tinyInteger('column_name')->default(0)->change();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
I'm getting an error:
Doctrine\DBAL\DBALException]
Unknown column type "tinyinteger" requested. Any Doctrine type that you use has to be registered with \Doctrine\DBAL\Types\Type::addType(). You can get a list of all the known types wit
h \Doctrine\DBAL\Types\Type::getTypesMap(). If this error occurs during database introspection then you might have forgot to register all database types for a Doctrine Type. Use Abstrac
tPlatform#registerDoctrineTypeMapping() or have your custom types implement Type#getMappedDatabaseTypes(). If the type name is empty you might have a problem with the cache or forgot so
me mapping information.
Am I doing something wrong?

Indeed Doctrine Dbal does not support tinyint you can read from their doc here
Unfortunately as well, laravel stated that tinyint cannot be changed. Check here
I need someone to prove this as wrong, because I had to use smallInteger because of this issue for one of my projects. I am thinking maybe boolean() might be the solution. I have not tried this though.

i hope that this will solve your issue
DB::statement("ALTER TABLE table_name CHANGE COLUMN column_name column_name TINYINT UNSIGNED NOT NULL");

Do This
Change tinyInteger to smallInteger
use Doctrine\DBAL\Types\Type;
use Doctrine\DBAL\Types\SmallIntType;
if (!Type::hasType('integer')) {
Type::addType('integer', SmallIntType::class);
}

I got same problem and found this solution. It worked for me. But it raise in me a question that why creator don't update to doctrine/dbal package. Maybe this solution can cause errors in some case? Hope someone explain in this answer.

Can you use boolean?
or
$table->smallInteger('column_name')->tinyInteger('column_name')->unsigned()->change();

If you are trying to convert a non-numeric column to an int column, you will get this error. The values cannot be converted.
You might run into this when converting an old string value to an id reference to a parent table.
Instead of trying to change the existing column, create a new column and delete the old:
// Add new int column
Schema::table('children', function (Blueprint $table) {
$table->unsignedTinyInteger('parent_id')->after('parent_slug');
});
// Convert old values to new
// Only runs on environments that already have data in db, by virtue of pulling all records from the parents table
foreach (\App\Parents::all() as $parent) {
\App\Child::where('parent_slug', $parent->slug)->each(function ($child) use ($parent) {
$child->update([ 'parent_id' => $parent->id ]);
});
}
// Drop old string column
Schema::table('children', function (Blueprint $table) {
$table->dropColumn('parent_slug');
});

!!! This solution is only for empty tables. Not if already populated.
Just drop and recreate the column with same name.
public function up()
{
// Drop and recreate because laravel don't allow to change to the tinyInteger type
Schema::table('your_table_name', function (Blueprint $table) {
$table->dropColumn(['rating']);
});
Schema::table('your_table_name', function (Blueprint $table) {
$table->tinyInteger('rating')->nullable()->after('some_column_name');
});
}

According to this https://github.com/laravel/framework/issues/8840 "BOOL" and "BOOLEAN" are both synonymous to "TINYINT" therefor just use "boolean" method instead of "tinyInteger", its the same in Laravel.

try this
Schema::table('table_name', function (Blueprint $table) {
$table->tinyInteger('column_name')->default(0)->change();

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

Pre-fill database table column field with HTML using Laravel migration

I have added a new column to a database table using Laravel migration as follows:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddFAQToStoreTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('store', function (Blueprint $table) {
$table->longText('FAQ')->after('description');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('store', function (Blueprint $table) {
$table->dropColumn('FAQ');
});
}
}
As a default value for FAQ, I want the following HTML pre-filled for all stores when I run the migration:
<div><span style="font-weight:600">Can we get our purchase delivered?</span><br/>
Yes, items purchased can be delivered. However, due to COVID-19 restrictions, we are expecting a 3-5 business days' delay.</div>
Is it possible to add a new column and simultaneously pre-populate it with a HTML block like above? If it's better practice to use database seeders, please advise as well. Thanks
You can update new column using Seeder and executing query.
1.Seeder - Link
2. executing query in your migration file
public function up()
{
Schema::table('store', function (Blueprint $table) {
$table->longText('FAQ')->after('description');
});
$html = '<div><span style="font-weight:600">Can we get our purchase delivered?</span><br/>
Yes, items purchased can be delivered. However, due to COVID-19 restrictions, we are expecting a 3-5 business days' delay.</div>';
DB::statement('UPDATE store SET FAQ='.$html);
}
I would recommend don't use this method, store a simple paragraph in your DB and add it to your blade template with the desired tag but If you insist and want to insert default data such as FAQ or other things, which don't have a specific structure, you should add them with Laravel Query Builder like below:
// define table
public function up()
{
Schema::table('store', function (Blueprint $table) {
$table->longText('FAQ')->after('description');
});
}
// insert some stuff
DB::table('store')->where('FAQ', '=', '')->update(array('FAQ' => '<div> . . . </div>'));
And use it in your blade template.

Syntax error or access violation: 1118 Row size too large

I have to help some friends develop an app in Laravel (even though I didn't ever use PHP & Laravel) and I've just cloned their repo.
When I'm running the migration, I get this error:
Syntax error or access violation: 1118 Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs")
I've just searched for it on Google and people were telling that some of my fields are too big, such as varchars, but they're not (or I don't think they are)
Here is my migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateStudentsTable extends Migration
{
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('nume')->nullable()->default(NULL);
$table->string('initiale')->nullable()->default(NULL);
$table->string('prenume')->nullable()->default(NULL);
$table->year('an_inmatriculare')->nullable()->default(NULL);
$table->integer('an_studiu')->nullable()->default(NULL);
$table->string('data_nastere')->nullable()->default(NULL);
//check this
$table->integer('tip_act_identitate_id')->nullable()->default(NULL);
$table->string('cnp')->nullable()->default(NULL);
$table->string('numar_serie')->nullable()->default(NULL);
$table->string('telefon')->nullable()->default(NULL);
$table->string('email')->unique()->nullable()->default(NULL);
$table->string('password');
$table->rememberToken();
$table->string('web')->nullable()->default(NULL);
$table->string('prenume_tata')->nullable()->default(NULL);
$table->string('prenume_mama')->nullable()->default(NULL);
$table->string('nume_casatorie')->nullable()->default(NULL);
$table->string('titlu_teza')->nullable()->default(NULL);
$table->text('comisie')->nullable()->default(NULL);
$table->text('adresa')->nullable()->default(NULL);
$table->integer('tip_cetatenie_id')->nullable()->default(NULL);
$table->integer('a_doua_cetatenie_id')->nullable()->default(NULL);
$table->string('sex')->nullable()->default(NULL);
$table->integer('tip_banca_id')->nullable()->default(NULL);
$table->string('cont_banca')->nullable()->default(NULL);
$table->integer('venit_pe_familie')->nullable()->default(NULL);
$table->string('alte_venituri')->nullable()->default(NULL);
$table->string('nume_liceu_absolvit')->nullable()->default(NULL);
$table->float('nota_bacalaureat')->nullable()->default(NULL);
$table->integer('localitate_domiciliu_id')->nullable()->default(NULL);
$table->integer('judet_domiciliu_id')->nullable()->default(NULL);
$table->integer('judet_nastere_id')->nullable()->default(NULL);
$table->integer('localitate_nastere_id')->nullable()->default(NULL);
$table->integer('orfan_de_un_parinte')->nullable()->default(NULL);
$table->string('numar_matricol')->nullable()->default(NULL);
$table->string('tip_act_identitate')->nullable()->default(NULL);
$table->string('numar_legitimatie')->nullable()->default(NULL);
$table->string('utilizator_id')->nullable()->default(NULL);
$table->string('status')->nullable()->default(NULL);
$table->string('dmy_facultate')->nullable()->default(NULL);
$table->string('dmy_domeniu')->nullable()->default(NULL);
$table->string('dmy_grupa')->nullable()->default(NULL);
$table->string('dmy_taxa')->nullable()->default(NULL);
$table->string('dmy_anstudiu')->nullable()->default(NULL);
$table->string('dmy_anuniv')->nullable()->default(NULL);
$table->integer('dmy_org_unit_id_pk')->nullable()->default(NULL);
//
$table->integer('portal_id')->nullable()->default(NULL);
$table->integer('moodle_user_id')->nullable()->default(NULL);
$table->string('moodle_id_number')->nullable()->default(NULL);
$table->string('moodle_username')->nullable()->default(NULL);
$table->integer('user_id')->nullable()->default(NULL);
$table->string('parola_initiala')->nullable()->default(NULL);
//
$table->string('observatii_student')->nullable()->default(NULL);
$table->integer('candidat_facultate_admitere_id')->nullable()->default(NULL);
$table->float('medie_admitere')->nullable()->default(NULL);
$table->string('an_emitere_diploma_facultate')->nullable()->default(NULL);
$table->string('profil_liceu')->nullable()->default(NULL);
$table->string('serie_diploma_facultate')->nullable()->default(NULL);
$table->string('numar_diploma_facultate')->nullable()->default(NULL);
$table->string('forma_finantare_facultare')->nullable()->default(NULL);
$table->string('an_absolvire_master')->nullable()->default(NULL);
$table->string('durata_studii_facultate_master')->nullable()->default(NULL);
$table->string('an_emitere_diploma_master')->nullable()->default(NULL);
$table->string('program_specializare_facultate_master')->nullable()->default(NULL);
$table->string('forma_finantate_facultate_master')->nullable()->default(NULL);
$table->string('nr_ani_bugetati_master')->nullable()->default(NULL);
$table->string('strada_domiciliu')->nullable()->default(NULL);
$table->string('nr_strada_domiciliu')->nullable()->default(NULL);
$table->string('bloc_domiciliu')->nullable()->default(NULL);
$table->string('apartament_domiciliu')->nullable()->default(NULL);
$table->string('cod_postal_domiciliu')->nullable()->default(NULL);
$table->string('program_specializare_facultate')->nullable()->default(NULL);
$table->string('nr_diploma_facultate_master')->nullable()->default(NULL);
$table->boolean('persoana_cu_dizabilitati')->default(0);
$table->integer('tara_liceu_id')->nullable()->default(NULL);
$table->integer('tara_domiciliu_id')->nullable()->default(NULL);
$table->integer('durata_studii_facultate')->nullable()->default(NULL);
$table->integer('facultate_absolvita_id')->nullable()->default(NULL);
$table->integer('nr_ani_bugetati_licenta')->nullable()->default(NULL);
$table->integer('tara_facultate_master_id')->nullable()->default(NULL);
$table->integer('judet_facultate_master_id')->nullable()->default(NULL);
$table->integer('localitate_facultate_master_id')->nullable()->default(NULL);
$table->integer('universitate_master_id')->nullable()->default(NULL);
$table->integer('tara_nastere_id')->nullable()->default(NULL);
$table->integer('liceu_absolvit_id')->nullable()->default(NULL);
$table->integer('localitate_liceu_absolvit_id')->nullable()->default(NULL);
$table->integer('judet_liceu_absolvit_id')->nullable()->default(NULL);
$table->string('an_absolvire_liceu')->nullable()->default(NULL);
$table->string('forma_inv_liceu_absolvit')->nullable()->default(NULL);
$table->string('act_identitate_serie')->nullable()->default(NULL);
$table->string('act_identitate_numar')->nullable()->default(NULL);
$table->string('eliberat_de')->nullable()->default(NULL);
$table->string('eliberat_data')->nullable()->default(NULL);
$table->string('etnia')->nullable()->default(NULL);
$table->string('valabilitate_pana_la')->nullable()->default(NULL);
$table->integer('erasmus')->nullable()->default(NULL);
$table->integer('localitate_populatie_mica')->nullable()->default(NULL);
$table->integer('urban')->nullable()->default(NULL);
$table->integer('rural')->nullable()->default(NULL);
$table->integer('maturi')->nullable()->default(NULL);
$table->string('studii_liceu_id_forma_invatamant')->nullable()->default(NULL);
$table->string('date_diploma_seria')->nullable()->default(NULL);
$table->string('numar_diploma_bac')->nullable()->default(NULL);
$table->string('date_diploma_anul')->nullable()->default(NULL);
$table->string('alte_observatii')->nullable()->default(NULL);
$table->string('date_diploma_emitent_id')->nullable()->default(NULL);
$table->string('stare_sociala_speciala_id')->nullable()->default(NULL);
$table->integer('judet_facultate_absolvita_id')->nullable()->default(NULL);
$table->integer('tara_facultate_absolvita_id')->nullable()->default(NULL);
$table->string('localitate_facultate_absolvita_id')->nullable()->default(NULL);
$table->string('forma_invatamant_facultate_absolvita')->nullable()->default(NULL);
$table->integer('universitate_absolvita_id')->nullable()->default(NULL);
$table->string('an_absolvire_facultate')->nullable()->default(NULL);
$table->string('situatie_medicala_speciala_id')->nullable()->default(NULL);
$table->integer('n_liceu_id')->nullable()->default(NULL);
$table->integer('date_diploma_localitate_emitent_id')->nullable()->default(NULL);
$table->integer('date_diploma_judet_emitent_id')->nullable()->default(NULL);
$table->string('sn_pasaport_strain')->nullable()->default(NULL);
$table->string('denumire_liceu_absolvit_strain')->nullable()->default(NULL);
$table->string('specializare_liceu_absolvit_strain')->nullable()->default(NULL);
$table->string('date_diploma_localitate_strainatate')->nullable()->default(NULL);
$table->string('an_sesiune_bac')->nullable()->default(NULL);
$table->string('localitate_liceu_absolvit_strain')->nullable()->default(NULL);
$table->integer('studii_liceu_id_n_specializare')->nullable()->default(NULL);
$table->integer('are_cnp')->nullable()->default(NULL);
$table->integer('student_strain')->nullable()->default(NULL);
$table->string('adresa_numar')->nullable()->default(NULL);
$table->string('localitate_nastere_strainatate')->nullable()->default(NULL);
$table->string('localitate_domiciliu_strainatate')->nullable()->default(NULL);
$table->string('liceu_institutie')->nullable()->default(NULL);
$table->string('liceu_institutie_eminenta')->nullable()->default(NULL);
$table->integer('candidat_olimpic')->nullable()->default(NULL);
$table->integer('admis')->nullable()->default(0);
$table->integer('respins')->nullable()->default(0);
$table->integer('conducator_doctorat_id')->nullable()->default(NULL);
$table->integer('limba_id')->nullable()->default(NULL);
$table->integer('nationalitate_id')->nullable()->default(NULL);
$table->integer('forma_invatamant_id')->nullable()->default(NULL);
$table->integer('forma_admitere_id')->nullable()->default(NULL);
$table->integer('etnia_id')->nullable()->default(NULL);
$table->integer('localitate_facultate_id')->nullable()->default(NULL);
$table->string('nota_disertatie')->nullable()->default('0.00');
$table->string('medie_licenta')->nullable()->default('0.00');
$table->string('medie_ani_studiu_licenta')->nullable()->default('0.00');
$table->string('medie_ani_studiu_master')->nullable()->default('0.00');
$table->integer('fost_student')->nullable()->default(0);
$table->integer('absolvent')->nullable()->default(0);
$table->integer('student_nr_ani_bugetat')->nullable()->default(0);
$table->integer('absolvent_nr_ani_bugetat')->nullable()->default(0);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('students');
}
}
And here are the errors:
I'm using Laravel 7 + MySQL.
In my mysql/maridb when this happens the fix is to make the row_format= dynamic.
Try this if it's either db.
ALTER TABLE your_table ROW_FORMAT=DYNAMIC;
More here
https://mariadb.com/kb/en/troubleshooting-row-size-too-large-errors-with-innodb/
You have to devide your table to multiple tables. And connect it each other with relation. And you can use Laravel relations hasOne and belongsTo.
For ex:
users
id
username
name
students
id
user_id
cart_number
...
user_address
id
user_id
address
street
...
And change data types to correct value

Laravel migration reset/refresh error ORA-01758 on Oracle Database

My Laravel migration keeps getting error when reset/refresh:
ORA-01758: table must be empty to add mandatory (NOT NULL)
The migration is as follow:
public function up()
{
Schema::table('kasbank', function (Blueprint $table) {
$table->dropColumn('name_bn');
$table->dropColumn('id_rekon');
$table->string('name_kb')->after('kode');
$table->integer('id_rek')->nullable();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('kasbank', function (Blueprint $table) {
$table->dropColumn('id_rek');
$table->dropColumn('name_kb');
$table->integer('id_rekon')->nullable();
$table->string('name_bn')->after('kode');
});
}
FYI, column id_rekon is initially nullable in the database.
What's missed from my migration?
The problem is that your table is not empty and the current rows will be given NULL as a default value, but the column is not allowed to be NULL.
You should be able to get around it by setting a default value.
From the Oracle docs:
However, a column with a NOT NULL constraint can be added to an
existing table if you give a default value; otherwise, an exception is
thrown when the ALTER TABLE statement is executed.
Try:
$table->integer('id_rek')->default($value)->nullable();
From: https://laravel.com/docs/5.5/migrations

How to disable Laravel eloquent Auto Increment?

I need an effective way to disable Laravel from auto incriminating the primary key of the table which I am going to insert data in.
Why? I don't check if there is any duplication between the DB and the inserted data so if there was any duplication I just handles it in a try-catch block.
The problem is if there was any failure Laravel counts it like I have inserted a row. So IDs column is not going to be in this order [1, 2, 3, etc], but in this [1, 4, 8, 20, etc].
I searched a lot about this issue and I have tried to use this line after the declaration of the class:
public $autoincrement = false;
Also
public $incrementing = false;
But they are not working.
I just want to use the AI of my DB. Not Laravel's one.
if you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false.
eg :
class UserVerification extends Model
{
protected $primaryKey = 'your_key_name'; // or null
public $incrementing = false;
}
in case of migration :
$table->integer('id')->unsigned(); // to remove primary key
$table->primary('id'); //to add primary key
refer : https://laravel.com/docs/5.3/eloquent#eloquent-model-conventions
Try public $incrementing = false;
In your model:
public $incrementing = false;
In your migration:
//Remove the default $table->id();
//second param is what auto-increments, default is false so can be skipped
$table->unsignedBigInteger('id', false)->primary();
A quick comment on all the other outdated or wrong solutions you see here:
$primaryKey does not need to be overridden unless the primary column is different than 'id'
You do not need to use the ugly DB transaction just to remove auto-incrementing! Keep using the lovely eloquent models and just use this answer.
There are 2 solutions to your problem.
First one is, as you said, disable the increment column. To do that, just go to your migrations, and change
$table->increment('id)`
to
$table->integer('id')
It will remove the primary key, to set the primary key, just go to your Model file and add this:
protected $primaryKey = 'column_name';
Second solution is what I prefer. Whenever inserting, updating or removing a record and even sometimes reading a record, use laravel's DB transaction. Here is an example:
DB::beginTranscation();
try {
$model = new Model;
$model->column_name = $value;
$model->save();
DB::commit()
return;
}
catch(exception $e) {
DB::rollback();
return;
}
This approach is better than remove the auto increment. But now it's upto you to choose.
You have to declare your new primary key in your table migration file:
$table->primary('new_key_column');
Of course you have to disable autoincrement in your model as you did.
You can do something like below
Table: author
Columns: id, name, active
class Author extends Model
{
/**
* Configure the Model variables
*
*/
protected $table = 'author';
protected $primaryKey = 'id';
protected $fillable = ['name', 'active']; // eloquent Will use only these columns as you are mentioning them as fillable.
public static function saveAuthor($data) {
$author = Author::firstOrNew(['name' => $data['name']]);
$author->name = $data['name'];
$author->active = 1;
$author->save();
}
}
Here in fillable you define the columns that you want to change or update through model. Rest fields behaviour will take according to mysql definition.
I hope this will help you.
*/ please test this one
public function up()
{
Schema::create('tablename', function (Blueprint $table) {
// $table->increments('id');
$table->integer('id')->unsigned()->nullable();
$table->string('name');
$table->string('info');
$table->timestamps();
});
}
// note:
add below line in model
public $incrementing = false;
This is an example for table created its name site_rules and this is the migration file which i add the following line to make id primary and auto incremented
//add this line to make id auto incremented from a specified value
DB::statement("ALTER TABLE site_rules AUTO_INCREMENT = 1;");
and this is the migration file code :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class SiteRules extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('site_rules', function (Blueprint $table){
$table->increments('id');
$table->string('name_ar');
$table->string('name_en');
$table->timestamps();
});
//add this line to make id auto increment from a specified value
DB::statement("ALTER TABLE site_rules AUTO_INCREMENT = 1;");
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('site_rules');
}
}
Try it
Sorry for taking your time guys,
The issue is if we tried to save any record in MYSQL whether it returned success or failure for any reason (like for duplication in my case),
MYSQL counts that the auto increment number was booked and any other coming record is not going to take it because of there may be more than an insertion process on the DB in the same time and waiting to know if the auto incrementally number is booked or not will cost MYSQL its speed.
So it is not a Laravel issue, its a MYSQL one.
I hope that it may help others.
Thank you all...
You can use
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->integer('matricule')->unsigned();;
$table->primary(['matricule']);
$table->string('nometprenom');
$table->string('age');
$table->string('adresse');
$table->string('telephone');
$table->string('login');
$table->string('password');
$table->string('type');
$table->engine = 'InnoDB';
});
}

Categories