image

Adding column in a table for existing table using laravel migration

By Team Globdig

#Alter Table 

In this Section of Laravel tips i have faced a problem during additions of a column to an existing table. This short snippet code show how to add an extra column to an existing table using migrations of laravel. This code is done in laravel 5.2.

This is from my projects school management system
Existing table Sections where i have some columns as id,sections_name,section_title.

To add an extra column we create a migrations as

php artisan make:migrate add_columnName_to_existingtableName

Folowing code and a code pictures shows how to add an extra column teacher id to and existing table sections

php artisan make:migrate add_teacher_id_to_sections

step-1

Note: teacher_id is id reference’s from existing table teachers

Now  what is included in the migration add_teacher_id_to_sections

Here’s what included following picture shows what we should include

bolsa de pierna decathlon
Adidas Stan Smith
sadarināšanās gredzeni
χρυσσες πλατφορμες
napihljivi fotelj merkur
nike air zoom pegasus 36 w
replika spor ayakkabı toptan
ted baker aurinkolasit
moschino tričko
νακ παπουτσια πεδιλα

step-2

We have added the schema for existing table sections as

Schema::table(‘sections’, function (Blueprint $table) {
       $table->integer(‘teacher_id’)->unsigned()->index();
       $table->foreign(‘teacher_id’)->references(‘id’)->on(‘teachers’)
       ->onDelete(‘cascade’);
});

In this short snippets of code we add a column of teacher_id as an added coloumn to sections table

Since, i have made a reference of teacher_id from an existing teachers table. You might be just using a normal column

Also for second part we have drop the column from the table and also a foreign key.
After, adding the code to this table we then run migrate refresh as

php artisan migrate:refresh

Then the added extra column will be added at last.

step-3.png

Hope this little help does make sense. if there is any doubt or quires please make a comment will give feedback. Keep coding !!!!