Search code examples
phplaraveleloquentmigrationmodels

Hi there, Can anyone explain about the laravel migration and model stuff


So i did read laravel docs, but it does not help me much, what i actually want to do is to setup a new database and create a table and insert some data.

But the problem is i don't even know the sequence to do that. like whether to build a model first or do a migration or run migration.

kindly do help me getting this stuff. thanks


Solution

  • Create database in laravel 1. Create migration - To create a migration, use the make:migration

    php artisan make:migration create_all_tables
    
    1. Once create your migration
      • Open migration "your_project\database\migrations"
      • Create schema
     Schema::create('preferences', function(Blueprint $table){
        $table->increments('id');
        $table->string('key', 50);
        $table->text('text');
        $table->timestamps();
      });
    
    - Your migration look like this
    
      <?php
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Database\Migrations\Migration;
    
      class CreateFlockTables extends Migration
      {
        public function up()
        {
          Schema::create('users', function(Blueprint $table){
            $table->increments('id');
            $table->string('user_name', 20); 
            $table->string('password', 60);
            $table->string('full_name', 50);         
            $table->string('contact_number', 50);
            $table->string('unit', 10);
            $table->text('address');    
            $table->rememberToken();
            $table->timestamps();
          });
    
          Schema::create('preferences', function(Blueprint $table){
            $table->increments('id');
            $table->string('key', 50);
            $table->text('text');
            $table->timestamps();
          });
        }
    
        public function down()
        {
          Schema::drop('preferences');
          Schema::drop('users');
        }
      }
    
    1. Database setting (forge is just example name you can give anything)
      • In ".env" file (local setting)

    DB_HOST=localhost DB_DATABASE=forge DB_USERNAME=root DB_PASSWORD=

    - In "your_project\config\database.php"
        'mysql' => [
            'driver'    => 'mysql',
            'host'      => env('DB_HOST', 'localhost'),
            'database'  => env('DB_DATABASE', 'forge'),
            'username'  => env('DB_USERNAME', 'root'),
            'password'  => env('DB_PASSWORD', ''),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'strict'    => false,
        ],
    
    1. Create database in phpmyadmin with name forge

    2. Run migration : php artisan migrate