Home » Beginner » Creating database table in laravel using migration
In the previous post, we saw how to set up a database in laravel. Now here we ‘ll create database table.
First create a database, here am using phpmydamin in localhost to create a new database named justLaravel,
edit the settings in .env file or/and database.php file as said in previous post, setting up databse in laravel
open .env file (located at ./env)
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=justLaravel DB_USERNAME=root DB_PASSWORD=
here am not using a password for my phpmyadmin, so i left it blank.
If you want to edit in database.php file(located at /config/database.php)
‘mysql’ => [ ‘driver’ => ‘mysql’, ‘host’ => env(‘DB_HOST’, ‘localhost’), ‘port’ => env(‘DB_PORT’, ‘3306’), ‘database’ => env(‘DB_DATABASE’, ‘justLaravel’), ‘username’ => env(‘DB_USERNAME’, ‘root’), ‘password’ =>; env(‘DB_PASSWORD’, ”), ‘charset’ => ‘utf8’, ‘collation’ => ‘utf8_unicode_ci’, ‘prefix’ => ”, ‘strict’ => false, ‘engine’ => null, ],
‘host’ => env(‘DB_HOST’, ‘localhost’), ‘port’ => env(‘DB_PORT’, ‘3306’), ‘database’ => env(‘DB_DATABASE’, ‘justLaravel’), ‘username’ => env(‘DB_USERNAME’, ‘root’), ‘password’ =>; env(‘DB_PASSWORD’, ”), ‘collation’ => ‘utf8_unicode_ci’, |
Now after the database is setup, we ll create a table using artisan make command, when we run php artisan make:migration tablename, it will create a new migration (/database/migrations/tablename.php)
When opened that file, it looks like,
<?php use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class SampleTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // } /** * Reverse the migrations. * * @return void */ public function down() { // } }
use IlluminateDatabaseSchemaBlueprint; use IlluminateDatabaseMigrationsMigration; class SampleTable extends Migration * Reverse the migrations. |
We write our schema for creating a table in function up( ), function down( ) is used to reverse the migrations, drop the table.
In funtion up( ), we ‘ll create a table named people with primary key ‘id’, first and last name, unique email, remember token, and timestamps.
public function up() { Schema::create(‘people’, function (Blueprint $table) { $table->increments(‘id’); $table->string(‘firstname’); $table->string(‘lastname’); $table->string(’email’)->unique(); $table->string(‘password’); $table->rememberToken(); $table->timestamps(); }); }
Schema::create(‘people’, function (Blueprint $table) { $table->increments(‘id’); $table->string(‘firstname’); $table->string(‘lastname’); $table->string(’email’)->unique(); $table->string(‘password’); $table->rememberToken(); |
Now we ‘ll run php artisan migrate
Now if we open phpmyadmin and we can see, the table people we just created,
We successfully created a table, for reference look at the previous post on setting up database.