Symfony2 like database creation command in laravel console? - laravel

I have used symfony2 console to create database. If I want to create a database named "symfony" I usually mentioned that name in parameters.yml file and run the below command in console
php app/console doctrine:database:create
But when came to laravel, I don't find similar command to create database in laravel. Can anyone help me to find out those command to create database directly from Laravel Console.

You can do that but you will have to create your own command.
First, run php artisan command:make CreateDatabase --command=database:create to generate app/commands/CreateDatabase.php
Then open that file and change it to this: (I left out all comments, but you can obviously keep them in there)
class CreateDatabase extends Command {
protected $name = 'database:create';
protected $description = 'Command description.';
public function fire()
{
DB::statement('CREATE DATABASE '.$this->argument('name'));
}
protected function getArguments()
{
return array(
array('name', InputArgument::REQUIRED, 'Database name'),
);
}
}
Now you only have to register the command in app/start/artisan.php:
Artisan::add(new CreateDatabase);
and you're good to go.
That's how you call it:
php artisan database:create your-desired-database-name
Alternative: artisan tinker
You can always use php artisan tinker to run PHP code (with Laravel bootstrapped):
php artisan tinker
> DB::statement('CREATE DATABASE your-desired-database-name');

As far as I know, you can use php artisan migrate to make migrations including creating tables from Laravel Console. However, you need to create and modify migration files first, where you can create or drop tables.
So if you want to create a table directly from Laravel Console using something like php artisan create database table ***, it is not possible.

I think you can not create database through command so go to app/config/database.php and set your database configuration. details here
'mysql' => array(
'read' => array(
'host' => '192.168.1.1',
),
'write' => array(
'host' => '196.168.1.2'
),
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
after setting you can create table through command
php artisan migrate:make create_user_table --table=users
it will generate a file to app/database/migrations name create_users_table. . . . . then you create your table following this link
and finally run this command php artisan migrate

Related

How to use global prefix for tables in Laravel 5

New in Laravel. Probably a silly question. I had setup database like this:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '3306'),
'database' => 'mydb',
'username' => 'myusername',
'password' => 'mypassword',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'admin',
'strict' => false,
'engine' => null,
],
Notice 'prefix' => 'admin'. This is because I want all tables related to the website's control panel be prefixed with admin, e.g: admin_users, admin_log, etc...
But I'm stuck at the very beginning. I'm trying to create migrations via artisan but it's not creating the tables with the prefix.
php artisan make:migration create_users_table --create=users
I'm expecting that to create a table named admin_users. But it's not.
Am I doing this right?
Laravel caches config files, so you may simply need to clear the cache:
php artisan config:clear
In addition to this, a better practice is to use the .env file to define your prefix, like this:
...
DB_PREFIX=admin_
...
and loading that in your config file, like this:
'prefix' => env('DB_PREFIX', 'abc')
This is how it should have been by default.
You're already loading the hostname and port from the .env file, so why not do it for the other values as well?
The migrations will be created without a prefix. After running php artisan migrate you should see tables with prefixes
Prefix does not includes underscore (_) by itself. In order to create admin_users You have to use admin_ prefix.
When generating migrations You will get plain table names, without prefixes.
With prefix = 'admin_'; this: Schema::create('users', function (Blueprint $table) {<...>}); will result in creation of admin_users table, because Laravel adding Your prefix under the hood by default.
TL;DR
Even though Your scheme displays table name without prefix, Laravel will create it with prefix.
You should use Schema::connection($name) method to apply the connection to the schema builder.
For some reason if you just set connection property - migration uses this connection to run queries but wont uses it during schema building.
The following is the migration code example that uses custom connection to create foo table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateFoo extends Migration
{
protected $connection = 'custom';
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::connection($this->connection)->create('foo', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::connection($this->connection)->dropIfExists('foo');
}
}
This code is tested in real app and works perfectly.
Laravel version: 8.40

How to prompt for database password when running Laravel 5 migrations

Laravel migrations need to be run with a particularly high level of privilege, as they perform DDL operations. I would like to run migrations as a named user without storing the password anywhere. This will require prompting the user for their password when they run the migration from the command-line. I cannot find any way to achieve this via connection configuration.
Is there a way to achieve this via the connection configuration?
If not, is there a way to perform the migrations with a thin layer of custom code over the top to establish the database connection in a custom manner? e.g. write a script/artisan command that does the prompting, connects to the DB, and then delegates the rest to Laravel's existing migration code?
If your requirement is to just ask the user for database credentials in order to run the migrations, then this can very easily be achieved by wrapping the artisan migrate command within another command that asks for appropriate credentials. So the steps below should suffice:
1. Create the new command:
artisan make:console MigratePrivilegedCommand --command="migrate:privileged"
2. Add the necessary code to handle user input and run the migrations in your new command class:
class MigratePrivilegedCommand extends Command
{
protected $signature = 'migrate:privileged';
protected $description = 'Run migrations as a priviledged database user.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
// Set the username and password for the
// database connection from user input
config([
'database.connections.mysql.username' => $this->ask('What is your username?'),
'database.connections.mysql.password' => $this->secret('What is your password?')
]);
// Call the migrate command and you're done
$this->call('migrate');
}
}
3. Register the new command in App\Console\Kernel.php:
protected $commands = [
...
\App\Console\Commands\MigratePrivilegedCommand::class,
];
And now you can run migrations that need privileged database credentials with this:
php artisan migrate:privileged
You can set a custom connection without any password in the config file and pass the password via CLI command to run the migrations.
In database.php config
'connection_without_password' => [
'driver' => 'mysql',
'host' => 'hostname,
'database' => 'database',
'username' => '$username',
'password' => '$password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Schema class includes a connection name option.
Schema::connection('connection_without_password')->create('users', function ($table) {
$table->increments('id');
});

Dynamic env-files (multiple databases) and artisan commands

I have a large project which will have each customer on their own separate database. To get this to work we use a custom .env-loader that loads each customers .envby checking the customers subdomain (unique to each customer).
However, of course this doesn't work with artisan commands. For instance, when I want to migrate, I will need to migrate all databases at once. So I've set up an Artisan command that fetches the .env-files and loop through them and then calls the default artisan migrate. But it is not working as expected.
I've tried everything; for instance:
$dotenv = new Dotenv('/env', '.test.env');
$dotenv->overload();
And:
app()->useEnvironmentPath('/env');
app()->loadEnvironmentFrom('.test.env');
And even:
config('database.connections.mysql.database', 'test_database');
As soon as I run $this->call('migrate'); the app defaults to the default .env and ignores all customizations at runtime. Does anyone have an idea on how I can overload the migration commands choice of database?
Note: I know that I can manually setup multiple connections in config/database.php (for instance like: Overriding Default Laravel database configuration for artisan migrate commands), however, image a few dozen customers and this would not be viable.
I had to do something similar with SQLite database that were being created by the console commands, and the only way I could get the migrations to run was by creating a database config on the fly:
Config::set('database.connections.'.$config_key, array(
'driver' => 'sqlite',
'database' => storage_path($database_name),
'prefix' => '',
));
And then I would call the migrate command:
Artisan::call('migrate', [
'--database' => $config_key,
'--path' => 'database/offline/'.$type.'/migrations',
]);
After a whole lot of issues I was able to sort it this way;
In Laravel 5 there seem to be a difference in Config::set(), config('config',['key' => 'value]) and config()-set('config', ['key' => 'value']).
After a lot of testing different variant we managed to get a solution this way;
$connection = 'connection';
$iterator = 0;
foreach ($files as $file) {
App::useEnvironmentPath('/env');
App::loadEnvironmentFrom('.file.env');
// Create a new connection "on the fly"
config()->set('database.connections.' . $connection . '_' . $iterator, [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
]);
// Call regular migration command
$this->call('migrate', ['--force' => true, '--database' => $connection . '_' . $iterator]);
$iterator++;
}
This manages to set multiple new connections to the MySQL-database, and then seed each one of them.
Thanks to #David Allen here for the inspiration.

Laravel: SQLSTATE[28000] [1045] Access denied for user 'homestead'#'localhost'

I just installed laravel and made a migration. But when i try to run it i get this error:
[PDOException]
SQLSTATE[28000] [1045] Access denied for user 'homestead'#'localhost' (using password: YES)
Can anyone tell me what is wrong? I think the Database.php file looks different than normal. Is this something new in the new Laravel?
My Database config:
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'LaraBlog'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'root'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
Hope someone can help me :)
I tried to make changes to database.php file present within config folder it looks something like this
'default' => 'mysql',
....
...
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'sample'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
I am not using any VM, I am using my local machine, with the database user as root and password a null.
I have also changed my .env file and it looks something like this:
APP_ENV=local
APP_DEBUG=true
APP_KEY=zLzPMzs5W4FNNuguTmbG8M0iFqhIVnsP
DB_HOST=localhost
DB_DATABASE=sample
DB_USERNAME=root
DB_PASSWORD=null
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Even after doing all the changes when I try to register using the registration form that is shipped with laravel, I try to add a user to my database I get the following error
After doing all the changes I cleared the cache and loaded it again and it seems to work for me now!
if any one is also facing the same issue just run the following commands
php artisan cache:clear
php artisan config:cache
I figured it out :) Had to chance the .env file :)
Is there any changes in the schemaes?
Shouldn't this work:
public function up()
{
// Create table with columns
Schema::create('users', function($table) {
$table->increments('id');
$table->string('username');
$table->string(Hash::make('password'));
$table->string('firstname');
$table->string('lastname');
$table->string('email')
$table->string('role');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Insert table to database
Schema::drop('users');
}
Try to check out the ".env" file in your root directory. These values are taken first. Yours are just the defaults if there are none given in the .env file.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Your_Database_Name
DB_USERNAME=Your_UserName
DB_PASSWORD=Your_Password
Make changes in the database.php file in **config > local >database.php
rather than change config > database.php file.
hope it will work ;)
practically when you are using localhost server like xampp, you create the database manually "homestead", such errors are due to missing database arguments. 100% percent working test it and see
hit your cmd and type in:
create database homestead;
i got the same issue after creating laravel project. The authentication command run successfully.
php artisan make:auth
But when i try to register or login i got the same error. I run the following command
php artisan config:clear
then stopped laravel application and also my server. after restarting my laravel app and server everything was ok.
Tried all the solutions here but no work for me
This Worked on the first try:
If you are using the PHP's default web server (eg. php artisan serve) you need to restart your server after changing your .env file values.
I found this solution from here laravel.io (Read the solution of Byjml)

DB:seed file for Laravel 4 working fine on local host, not working on Mediatemple gridserver?

I have a Laravel 4 db:seed file that I am trying to use on mediatemple gridserver. I was able to run a migration with artisan fine (php artisan migrate), and make the tables, but I am not able to seed the tables. This database seeding worked fine on local host. It is only now on a live server that I am experiencing any issues with it. Here is the seed file:
ArtistsTableSeeder.php:
class ArtistsTableSeeder extends Seeder {
public function run()
{
// Uncomment the below to wipe the table clean before populating
// DB::table('artists')->delete();
$artists = array(
);
$Artists = [
['stage_name' => 'Blah', 'city' => 'Blah', 'state' => 'blah', 'video_path' => 'youtube.com', 'image_path' => 'filepickerimage', 'soundcloud_profile' => 'https://soundcloud.com/', 'description' => '', 'created_at' => new DateTime, 'updated_at' => new DateTime]
];
// Uncomment the below to run the seeder
DB::table('artists')->insert($Artists);
}
}
It is spitting out this error:
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","message":"syntax error, unexpected '['","file":"\/nfs\/c09\/h04\/mnt\/139243\/domains\/crowdsets.com\/html\/app\/database\/seeds\/ArtistsTableSeeder.php","linemichaelsutyak.com#n26:/home/139243/domains/crowdsets.com/html$ php artisan db:seed
It is complaining about the line that starts the array:
$Artists = [
I have no idea why this is happening. A little help would be appreciated. Thank you!
That syntax error you get is probably caused by a feature that has been added in PHP 5.4 (short array syntax), so I'd guess your hoster still runs 5.3.x.
You should check the PHP version on the mediatemple grid server and update it if necessary.

Resources