Showing posts with label Migration in Laravel. Show all posts
Showing posts with label Migration in Laravel. Show all posts

Laravel Model and Database Migration From Scratch

Laravel Database Migration


Laravel Database Migration is way through which we build and maintain the Database Schema. Migration is Version Control of Your DB, which will allow Developer team easily to modify and share the DB Schema.

Laravel DB Migration provide the facility for those who is not able and poor in maintaining, updating Database.

Migration In Laravel contain by default Two method up() method is called when a DB is modified or changed. Whereas, the DB Migration down() method is called when DB is reverted back.


create migration in laravel

Step 1: Create Laravel Project with Name anyQuestion using Composer. Command to create project in laravel is below.

composer create-project --prefer-dist laravel/laravel anyQuestion "6.*"

anyQuestion is our Laravel Project name. Below is the Screen what will appear while creating the project using Command prompt.


Step 2: Create Database named with anyQuestion_db in Xampp or whatever server tool you use. Open .env file in your laravel project and configure your Database with password and all.

Step 3:  Use Php Artisan Command to create model and controller in your project.

php artisan make:controller controllerName

This above artisan command will create normal controller without default function.

php artisan make:controller controllerName --resource

This above Artisan Command will create controller with default function in it. All the default Function list is below.

  • public function index(){ }
  • public function create(){ }
  • public function store(Request $request){ }
  • public function show($id) { }
  • public function edit($id) { }
  • public function update(Request $request, $id){ }
  • public function destroy($id) { }

If we are creating the Controller with --resource then by default all the above function will be created and creating route for all the above function will be time consuming process. So view the route list first using below artisan command. below command will give you all the route list.

php artisan route:list

How to define single route which will point all the above function based on the requirement.

 Route::resource('route-name','controller-Name');

Again hit the php artisan route:list  And you can view all the route list for default controller function.

Now create Model using artisan command, below is the command

php artisan make:model model-Name

Above command will create the simple model with sample model name what is provided with the command.

Laravel Run Migrations


Database migration concept start with model here. Database migration in Laravel provide the facility to create, manage and modify the database. Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

Now check your Migration folder inside Database Folder in the anyQuestion project root.

In the migration folder the migration file will be created and if you open that you will get default up() function and down() function.

   public function up()
     {
        Schema::create('post_masters', function (Blueprint $table) {
            $table->increments('id');
            $table->timestamps();
        });
     }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_masters');
    }

If you check the post_master migration file, In up() function we are creating post_masters table.  By default there is 'id' column and the timestamp which will give us the 'created_at', 'updated_at' column.

Once you have created the model with migration you don't have to touch the Database to create table. You can directly migrate the file using below command which will create the table in the database. To add column or remove column you just make change in the migration file. and using artisan command it will reflect in the Database. Command to migrate the files.

Before Migration go to Provide Folder and Open the AppServiceProvider.php file and add this line of code. Open AppServiceProvider.php file

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Schema::defaultStringLength(191);
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        // 
}

Once change is made run the migration Command which is below for your reference.

php artisan migrate

The Artisan command will run it will create the table automatically in the Database..

How to insert the record in Database using Artisan Command


Insert Data Using Tinker

laravel Seeding and Datatbase from Scratch


Database Migration and Database seeding is one of the most amazing feature of Laravel Framework. Database seeding is feature through which we insert the dummy record / data using Seed Class in the DB table for testing purpose. Seed Classes name can be anything but it is good to follow the standard practice for naming Convention, Example of Seed Classes is UserTableSeeder, UserSeeder etc.

All the Seeder Classes is stored in database / seeds Directory folder. By default DatabaseSeeder is defined in seeds Folder.

Whenever we download the laravel project Folder at that time by default PHP Faker Package is also get installed in the Project folder. Php Faker package help us to generate the Fake data for Database seeding.

Artisan command to create the Seeder Class for populating Data in the table.

php artisan make:seeder seederName

SeederName whatever it get created using Artisan Command will be stored in database / seeds Directory. By Default Seeder class contain only one method that is run().

Artisan Command to run the seed Class is below for your Reference.

php artisan db:seed

php artisan db:seed --class UserTableSeeder

php artisan db:seed artisan command will run the DatabaseSeeder Class by default, which can call other seed class. If you want to run some particular Seed Class to populate the Database table then we have to use php artisan db:seed --class seederName

DatabaseSeeder Class code is below what we get in the database/seeds directory while installing the project.


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()   // By Default Artisan Command will Run This
    {
        // $this->call(UsersTableSeeder::class);
    }
}

How to Implement The Laravel Database Seeding?


Step 1:  Create Model with migration using Artisan Command. Below is the command to create Model with migration.

  php artisan make:model model-Name  -m (-m is for migration )

Now check your Migration folder inside Database Folder in your laravel project.

In the migration folder the migration file will be created and if you open that you will get default up() function and down() function for the table whatever it is. I have modified the post_masters table by adding First_name and Last_name. 

   public function up()
     {
        Schema::create('post_masters', function (Blueprint $table) {
            $table->increments('id');
            $table->string('First_name', 50);
            $table->string('Last_name', 50);
            $table->timestamps();
        });
     }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('post_masters');
    }


Method 1st to implement the Database Seeding in Laravel

Step 2: Now go to database / seeds directory and open the default DatabaseSeeder.php file which we get by default. Below is the code for your reference purpose. Start writing the code in the run() function.


use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run() 
    {
        DB::table('post_masters')->insert([
            'First_name' => Str::random(10),
            'Last_name' => Str::random(10),
        ]);
    }
}

In the above code Str::random(10) will generate random strong which will  have the length 10 Character. Run the Artisan Command for Database table seeding, once it will run It will generate the random string that can be anything which will not have any sense. This Artisan Command will call the run() method by default.

php artisan db:seed

So now we will use PHP Faker package to generate some sensible data in below method.

Method 2nd to implement the Database Seeding in Laravel

In 2nd Method for each Migration Table we will create individual seeding class following the Naming convention using Artisan command and by using PHP Faker package for generating the data.

So Let's start with Example, create separate seeding Class for post_masters  table using Artisan Command. Below is the Command for your reference.

php artisan make:seeder PostMasterSeeder

Once you run the above Artisan command you will get the PostMasterSeeder.php file in database/seeds Directory. Below Code is the reference of  PostMasterSeeder.php. Now we will write the code for our Post_master table to create the fake Data for testing.

use Illuminate\Database\Seeder;
class PostMasterSeeder extends Seeder {     /**      * Run the database seeds.      *      * @return void      */     public function run()     {         //     } }

You can read more about the PHP Faker here Now Open the DatabaseSeeder.php file and call the PostMasterSeeder.php file for seeding.

use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder {     /**      * Run the database seeds.      *      * @return void      */     public function run()     {           $this->call(App\PostMasterSeeder::class, 50);
    } }

Now go to database / factories root folder there by default UserFactory.php will be there. We will create the PostMasterFactory using Artisan Command. Below is the Artisan command for your reference.

                                    php artisan make:model PostMasterFactory   

Above Artisan command will create the Factory for Post_master table. By Default it will give the code which is below for your reference. Above Command will create the Factory without model detail.

use Faker\Generator as Faker; $factory->define(Model::classfunction (Faker $faker) {     return [             ]; });

                        php artisan make:factory PostMasterFactory --model=PostMaster

Above  Artisan command above will create the Factory with model which we can use for Database seeding for particular table.
use Faker\Generator as Faker; $factory->define(App\PostMaster::classfunction (Faker $faker) {     return [         //     ]; });

Now add the code in the above PostMasterFactory.php file.

use Faker\Generator as Faker;
$factory->define(App\PostMaster::classfunction (Faker $faker) {     return [         'First_name' => $faker->firstName,         'Last_name' => $faker->lastName,     ]; });

After doing all the previous Step run the Artisan Command to generate the record. Artisan command is below for your reference.

                                                        php artisan make:seed

Finally it will generate the sensible Fake data in Post_master table.

Our Feature Post

There is a tree between houses of A and B If the tree leans on As House

    There is a tree between houses of A and B. If the tree There is a tree between houses of A and B. If the tree leans on A’s House, the t...

Our Popular Post