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
1 2 3 4 5 | Schema::create('users', function($table) { $table->DataType('ColumnName'); }); |
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:
1 2 3 4 5 | Schema::create('users', function ( $table) { $table->increments('id'); $table->string('name'); }); |
Demo:
Run the newly created Route on the browser
Result:
Some common column creation commands:
Column 1 | Column 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.
1 2 3 4 5 | Schema::table('users', function($table) { //TODO }); |
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:
Access the route with a browser:
Result:
To change the name of column Name1 to Name2, use the renameColumn command:
$table->renameColumn('Name1', 'Name2');
. The same way to add columns:
Results after running:
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:
Results running in the browser:
Results in the database:
To delete a table, we use the drop method:Schema::drop('tableName');
For example, you want to delete the user table:
Access the route in the browser:
Result: