Using Schema Builder to create and edit tables in Laravel

Tram Ho

Schema Builder is a Laravel class that helps us work with the databases that Laravel supports with predefined functions. In this article, I would like to introduce how to create and edit tables in the database simply with Schema Builder.

To be able to use Schema Builder you must first connect to the database and call its namespace Illuminate\Support\Facades\Schema .


1. Create a table

To create a table we use the create method

Where DataType is the data type of the column and ColumnName is the name of the column.

For example, I want to create a table with 2 fields, id and name:

Demo:

image.png

Run the newly created Route on the browser

image.png

Result:

image.png

Some common column creation commands:

Column 1Column 2
$table->char(‘name’, 4);create column name with data type char with length 4
$table->date(‘created_at’);create column create_at with data type date
$table->integer(‘votes’);create votes column with integer data type
$table->timestamp(‘added_on’);create added_on column with data type as data add time
$table->string(’email’);create email column with data type is string
$table->float(‘amount’);create column amount with data type float

You can also refer to the link :https://laravel.com/docs/5.0/schema

2. Editing table

To update an existing table, we use the **table ** method.

To add columns, we use the same statement as adding columns when creating a table: $table->DataType('ColumnName');

For example, add an email column to the users table:

image.png

Access the route with a browser:

image.png

Result:

image.png

To change the name of column Name1 to Name2, use the renameColumn command:

$table->renameColumn('Name1', 'Name2');. The same way to add columns:

image.png

Results after running:

image.png

To delete columns Column1 and Column2 in the table we use the dropColumn command:

$table->dropColumn(['Column1','Column2']); . The same way to add columns

To rename table Tb1 to Tb2: Schema::rename('Tb1', 'Tb2');

For example, if you want to rename the users table to user:

image.png

Results running in the browser:

image.png

Results in the database:

image.png

To delete a table, we use the drop method:Schema::drop('tableName'); For example, you want to delete the user table:

image.png

Access the route in the browser:

image.png

Result:

image.png

Share the news now