Laravel Migration Operations and Common Errors
Common Errors Related To Laravel Migration
This week, I will talk to you about migration with Laravel and some common Laravel migration errors.
But first, what is migration? And why do we use it?
Let’s look for the answer within these lines:
Friends who make .net development to this -migration event will remember because of -Entity. I can say that migrations are a layer that separates us and the database. Facilitating the project to stand up in another environment. Providing version control of the database architecture and we can call it an intermediate layer in which we can perform database operations within the project without going to SQL. Basically, we can say that we use our database for managing and versioning according to our project. -migration -Laravel in our project
Migrations in our Laravel project
database/migrations
They are located under the folder. In Laravel, you have already created your first project.
create_user_table create_user_password_reset_table
Migration files will be ready to run. You can examine them. The first command we need to know is that we will start migration processes with an example first.
php artisan make:migration helloWorld
Here we use a name that indicates the name and status of the table after making the migration, such use has been developed as standard and we make this naming as lower camel case. Sample;
php artisan make:migration helloWorld
When you run this command, you will see that your migration file named _create_phone_model_table has occurred along with the timestamp you run. The inside of the file should look like this.
use IlluminateDatabaseMigrationsMigration; use IlluminateDatabaseSchemaBlueprint; use IlluminateSupportFacadesSchema; class CreatePhoneModelTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('phone_model', function (Blueprint $table) { $table->bigIncrements('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('phone'); } }
The first part we need to know here is the details of Schema in another article, but there are two basic uses. The table here we will use the “create” method because we want to create a table where we will hold the phone models. Then we continue with the species we know from the database, you can reach all the species here. I will talk about a few of them here. We have a scenario like this. We make a table where we will keep the phone models and features. First of all, I think these columns should be.
- Brand
- Model
- Year of production
- Versions
- Platform
based on basic features like. Now, let’s continue our operations. Our Ups function is our function that will be executed when migration runs. After the last edit, up should look like this;
Schema::create('phone_model', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('brand')->comment('phone brand'); $table->string('model')->unique()->comment('phone model'); $table->date('year')->comment('phone year of manufacture'); $table->float('version')->comment('phone version'); $table->enum('platform', [1, 2])->comment('phone platform : 1 Android , 2 IOS '); $table->timestamps(); });
Now, let’s clarify a little bit here. If our id column is defined in bigIncrements type, otherwise it comes as autoincrement = true. If you want to define another big integer, for example, if we defined the version bigIncrements here, we would encounter an error like this.
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
What this means is that there cannot be more than one auto increment column in a table. If you are going to define a second bigIncrements, there are two methods.
1.Method
$table->bigIncrements('version')->autoIncrement(false);
2.Method
$table->unsignedBigInteger('version',false);
Laravel migration errors:
So we talked about an error and the solution for that error. Let’s continue with our scenario and explain it. As you know, string corresponds to varchar. In SQL, if you do not specify the length or make any other settings, it comes to 255 initially. if its length
$table->string('brand',100);
You can specify. Our other feature is “comment”, although you can use the part where we enter a comment in this column, the description lines are unfortunately not used in our sector. We leave a note for our teammates to understand. Our other feature is “unique” as it is understood from this name if you try to add more than one record with the same name, which indicates that there can be only one of each data in this column. SQL will give an error. The type, which means that we will keep the date in a subject database that does not need much explanation on the date, is also a type that we use for fractional number types. Our other type “Enum” indicates that one of the values in the series should be selected. Again, you will encounter one of Laravel migration errors when you enter a value that is not defined here during registration. Another function that Laravel brings to us is “timestamps”, which allows our table to automatically define a created_at and updated_at columns. If you have not had a problem so far, we can now run migration. Run the following code.
php artisan migrate
you should see an output like this.
Migrating: 2020_03_28_201311_create_phone_model_table
Migrated: 2020_03_28_201311_create_phone_model_table (0.04 seconds)
If you have encountered this output, the operation is successful. If you get an error, you can ask in the comments.
If we continue with the scenario, our phone models table is ready now, but let’s assume that new updates came to my mind, for example, we wanted to bring phone brands from another table and we wanted to mark them with a key. For this situation, we first need to create another migration for phone brands.
php artisan make: migration createPhoneBrands
then we add our additional content. Let there be options such as Brand Name, Logo, Promotional text. It should look like this;
Schema::create('phone_brands', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name', 100); $table->string('logo_url'); $table->text('description'); });
We removed it because we don’t want timestamp here. We create this table.
php artisan migrate ... Migrating: 2020_03_28_201558_create_phone_brands Migrated: 2020_03_28_201558_create_phone_brands (0.02 seconds)
yes, it is very successful so far, but we will have to make a change in the model table. we create a new migration for this and make the necessary changes.
php artisan make: migration changeBrandColumnTypeAndAddForeignKey
Do not get stuck on naming, you can name it as you can understand it. Just follow the naming standard. The up function of our file came empty because we did not specify it as Create. Let’s make the necessary changes. Inside of Up function
Schema:: table('phone_model', static function (Blueprint $table) { $table->BigInteger('brand')->change(); $table->foreign('brand')->references('id')->on('phone_brands'); });
and then
php artisan migrate
and we got another mistake.
Changing columns for table “phone_model” requires Doctrine DBAL; install “doctrine/dbal”.
Actually, the solution is simple, it also writes in content. To make changes to the database, we need to install the doctrine / dbal package.
composer require doctrine/dbal
then let’s do the migrate process again. If you are using Mysql ≤ 5.7, this time you are likely to get an error like this.
Unknown database type enum requested, Doctrine DBAL Platforms MySQL57Platform may not support it.
Of course, there is a solution, we will add it as follows. We add the following to our Schema class.
DB::connection() ->getdoctrineschemamanagis() ->getdatabaseplatform() ->registerDoctrineTypeMapping('enum', 'string');
we re-migrate after this last addition. Let’s again an error
SQLSTATE [42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
Let’s interpret why this time. Again problem $table-> bigInteger (‘brand’) -> change (); definition of bigInteger is defined as autoincrement. In such a case, he would give an error.
Schema:: table('phone_model', function (Blueprint $table) { $table->integer('brand', false)->charset(null)->Change(); $table->foreign('brand')->references('id')->on('phone_brands'); });
If it is an error
SQLSTATE [HY000]: General error: 1215 Cannot add a foreign key constraint
Because our brand’s table was also defined as brand Big Integer. here, the brand in our model table is defined as an integer. We encountered this situation because the species did not match. Let’s come to the final version of the employee version, which should be the main one.
public function up() { DB::connection() ->getDoctrineSchemaManager() ->getDatabasePlatform() ->registerDoctrineTypeMapping('enum', 'string'); Schema::table('phone_model', function (Blueprint $table) { $table->unsignedBigInteger('brand', false) ->charset(null) ->change(); $table->foreign('brand') ->references('id') ->on('phone_brands'); }); }
When we migrate this way again, we should now be able to see the following message.
Migrating: _change_brand_column_type_and_add_foreign_key Migrated: _change_brand_column_type_and_add_foreign_key (0.09 seconds)
Now our tables are connected to each other and we made the changes we wanted. When we want to add another column to the table, we use the after or before method, not change this time. Let’s do this from an example. For example, if we do not want to show the model on the front, we can put a flag and define a boolean. So 1 can be displayed on the front. I’m creating a migration.
php artisan make: migration addStatusColumnToPhoneModel
and we organize it like this.
public function up() { Schema::table('phone_model', static function (Blueprint $table) { $table->boolean('status') ->after('platform') ->default(1); }); }
Here we added a flag called “Status” and set its type as “Boolean” and we add this column after the platform column, and we specify that it is 1 by default. And
Migrating: _add_status_column_to_phone_model Migrated: _add_status_column_to_phone_model (0.05 seconds)
Buddha also worked successfully. We will be talking about undoing and other features later. I will finish the subject “Laravel migration errors” off here without further ado.
Good Coding for Everyone 🙂