PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, April 19, 2022

[FIXED] How to create a mysql db with Laravel

 April 19, 2022     laravel     No comments   

Issue

I'm using Laravel 5.2. I've setup my first migrations and I want to run them. From the video tutorial it doesn't explain how to create a mysql db. I know I can do this manually in phpmyadmin but is there a Laravel way to do it?

This will install the migrations table:

php artisan migrate:install

Is there a similar command that will create the DB?

I'm thinking the process should be:

php artisan DB:install (or similar command)

Install the migrations table:

php artisan migrate:install

Run the migrations:

php artisan migrate

and to rollback the migrations:

php artisan migrate:rollback

Solution

Nothing provided out of the box but you could make your own command that could do this for you:

php artisan make:console CreateDatabase
// Note, in 5.3 this is make:command

Then in app/Console/Commands you'll find CreateDatabase.php. Open that sucker up and let's make a few changes:

protected $name = "make:database";
// in Laravel 5.3 + it's protected $signature

Then down below in your file we need a new function:

protected function getArguments()
{
    return [
        ['name', InputArgument::REQUIRED, 'The name of the database'],
    ];
}

Then we'll make another function called fire() which will be called upon invocation of the command:

public function fire()
{
    DB::getConnection()->statement('CREATE DATABASE :schema', ['schema' => $this->argument('name')]);
} 

And now you can just do this:

php artisan make:database newdb

Now you'll get a newdb database created for you based on your connection configuration.

Edit Forgot the most important part - you need to tell app\Console\Commands\Kernel.php about your new comand, make sure to add it to the protected $commands[] array.

protected $commands = [
    ///...,
    App\Console\Commands\CreateDatabase::class
];


Answered By - Ohgodwhy
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing