7

is there anyway I could setup(create) database from migration? I want to run migrate and seed, but beforehand it should create database first.

Any suggestions ?

Thanks

ans4175
  • 432
  • 1
  • 9
  • 23
  • You would potentially need higher permissions than you would want to give to your Laravel user in order to create a database. It might be better to create your database and user separately from your application code using a privileged account. – Henry Nov 28 '17 at 02:09

2 Answers2

7

You could create custom artisan command and run it before migrate command.

Inside the command use raw query, you can try something like this:

DB::statement('CREATE DATABASE :db', ['db' => $newDatabase]);
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • He also needs to modify the environment parameters – Hongbin Wang Apr 29 '16 at 06:57
  • what environment parameters? – ans4175 Apr 29 '16 at 06:58
  • @HongbinWang, true. ans4175, you'll also need to create new connection to use created database. – Alexey Mezenin Apr 29 '16 at 07:01
  • @ans4175, I've found pretty elegant example of doing that. It's for Laravel 4, but it should work for Laravel 5 too. Look for JohnathonKoster's post here: http://laravel.io/forum/09-13-2014-create-new-database-and-tables-on-the-fly – Alexey Mezenin Apr 29 '16 at 07:04
  • Practically I want to create database before running test in wercker – ans4175 Apr 29 '16 at 07:20
  • I have no idea why this question is upvoted. It's apparent no one has tried it because PDO doesn't support binding for database, table, or column names. The `:db` part can only be for values in queries, not for names. https://stackoverflow.com/a/53210496 – Joel Mellon Jan 27 '22 at 15:48
0

you can do this by new Artisan Command...

php artisan make:database {database-name} {connection-name}

but you have to creat this command first.

check this link

How to create new empty database with Laravel over Model

pankaj
  • 1
  • 17
  • 36
  • I guess this command doesn't exist by the latest version. I tried and it said "Did you mean." and database is not among the suggested keywords. – tolga Apr 06 '20 at 12:46