Laravel Database: Migrations

Laravel migration helps us to easily manage and handle database table like modifying, creating and updating a table . After successful laravel installation, make sure you have generated the key for application .

Generating Key :

php artisan key:generate

The key is a random string of 32 characters used for securely encrypting sessions.

Generating migrations :

php artisan make:migration create_users_table

The above commands create a migration in your migrations folder.

Database/migrations

In laravel and in most MVC , models relates to a table of the database . While creating a database table and model , we should always follow below tips :

  1. Model name should be singular .
  2. Table name should be plural .

Let’s assume , User (singular) is a model and users (plural) is a table . We should follow this tips so that we can use laravel eloquent functionality which makes it easier to handle relationship and others .

For an instance, if we follow above rules then we don’t need to mention table name in Model . The model will know the table itself .

For easily creating model with migration :

php artisan make:model User –migration

or

php artisan make:model User -m
public function up() {
     Schema::create('users', function (Blueprint$table) {
       $table->increments('id'); //primary incremental number
       $table->string('name');
       $table->string('email')->unique(); // unique
       $table->string('password',60); // max : 60
       $table->rememberToken();
       $table->timestamps();
     });
}

This above function “up” will create a table named users with columns like id, name, email, password , remember_token (for remember me ) and timestamps which creates two timestamp like created_at and updated_at . and function “down” :

public function down() {
      Schema::dropIfExists('users');
}

This function call will drop our table users .

Now , You can run :

php artisan migrate

Run above command on terminal .

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest