Can't Figure out how to set up a database on Laravel - php

This is becoming a really annoying problem. I am following the Quick setup directions on laravel.com. I have followed all the steps until I have to go:
php artisan migrate
The result is:
[PDOException]
SQLSTATE[42000] [1049] Unknown database 'database'
migrate [--bench[="..."]] [--database[="..."]] [--path[="..."]] [--package[="..."]] [--pretend] [--seed]
And I go back and check the database.php file and it reads:
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),
Afterwards, I go to localhost:8000/users and it displays:
PDOException
SQLSTATE[42000] [1049] Unknown database 'database'
open: /Users/benamorgan/Sites/run-away-world/vendor/laravel/framework/src/Illuminate/Database/Connectors/Connector.php
*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}
I have been trying to change the database name, provide a root password, start and stop mysql, change the naming in every possible way for database, change localhost to 127.0.0.1. I don't know what to do, hence I'm stopping by here to ask where I messed up.

Laravel doesn't create databases for you, you need to do it on your own. Log in to mysql and create your database, then provide the name in your db config.
You can do it quickly in your console:
echo "create database my_database" | mysql -u root -p
then in your config change the database name:
'database' => 'my_database',

To add, make sure that you are using the MySQL driver in the config file, although this must be obvious.
again make sure the database in MySQL is created prior and you are using the right credentials (User, Key)

Related

Laravel migration error - could not find driver - Illuminate\Database\QueryException

I'm trying to run a migration following this tutorial https://www.youtube.com/watch?v=074AQVmvvdg&list=PL4cUxeGkcC9hL6aCFKyagrT1RCfVN4w2Q&index=13
I think the tutorial might be out of date because when I enter php artisan migrate; I get this error:
Illuminate\Database\QueryException
could not find driver (SQL: select * from information_schema.tables where table_schema = pizzahouse and table_name = migrations and table_type = 'BASE TABLE')
at C:\Users\jonke\Documents\laravel\pizzahouse\vendor\laravel\framework\src\Illuminate\Database\Connection.php:703
699▕ // If an exception occurs when attempting to
run a query, we'll format the error
700▕ // message to include the bindings with SQL,
which will make this exception a
701▕ // lot more helpful to the developer instead
of just the database's errors.
702▕ catch (Exception $e) {
➜ 703▕ throw new QueryException(
704▕ $query, $this->prepareBindings($bindings), $e
705▕ );
706▕ }
707▕ }
1 C:\Users\jonke\Documents\laravel\pizzahouse\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDOException::("could not find driver")
2 C:\Users\jonke\Documents\laravel\pizzahouse\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70
PDO::__construct()
I've read the comments on the video, where I found the solution to an earlier error. I've tried following suggestion on this page: https://github.com/laravel/framework/issues/24711 which seemed promising but no joy.
I found pages on this website describing the same error message with different causes. One looked promising but vscode didn't like the sudo apt-get bits. (I've lost the link, sorry).
This one had a similar title but was no good: Migration in Laravel 5.6 - could not find driver
I also tried following the official docs: https://laravel.com/docs/8.x/migrations
How am I able to create the DB in the command line in vscode but not run the migration? I don't get it! I've been clicking around in circles for a couple of days now, can someone help me please?
Thanks
Added JonKemm Solution
It was the c:\php7/php.ini - needed to modify a line - uncomment this line: extension=pdo_mysql Answer found here: https://stackoverflow.com/a/25137901/16714187
If any other case your problem not solve try further
You have to add driver connection reading code. You can find in
config->database.php
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
If you didn't find this in b/w
'connections' => [
...
],
Above version copied from Laravel Framework 6.20.30
If you missing something from these code from older laravel version try to compare or add some codes.
If you didn't find mysql code there
Copy my code and paste into your file, If you find any error comment below.
It was the c:\php7/php.ini - needed to modify a line - uncomment this line:
extension=pdo_mysql
Answer found here: https://stackoverflow.com/a/25137901/16714187

Codeigniter: using a database to store database names for multiple users

Using Codeigniter 3.0.6
Until now I have been using the standard setup for Codeigniter. I have a database and all connects just fine. The question that I'm having trouble with is that I want to add a 'global_accounts' database, from which, depending on the user currently logged in will choose the database to load.
Global_Accounts
--------------------------------------------------------
user | coolUser | user2
pass | coolPassword | passy
url | coolestsite.mysite.com | u2.mysite.com
database_name | coolestsite_application_db | u2_application_db
The application data/schema doesn't really matter as far as I'm concerned. What I want (and am going to set up, but outside of the scope for this question) is for when a user registers, they will fill out user, pass and url, and db_name will be automatically created. The script will then create a new database with that name, creating a blank copy of the application db for the user.
So for now, we're hard coding that, so we can assume that it's working perfectly.
What I want is inside Codeigniter's database.php file:
$db['default'] = array(
'dsn' => '',
'hostname' => 'mysite.com',
'username' => 'root',
'password' => 'pass',
'database' => 'coolsite_application_db'
...etc
);
Instead of hard coding this file, I want to be able to do something like this:
$db['global'] = array(
'dsn' => '',
'hostname' => 'mysite.com',
'username' => 'root',
'password' => 'pass',
'database' => 'global_accounts'
...
);
$db['default'] = array(
'dsn' => '',
'hostname' => 'mysite.com',
'username' => 'root',
'password' => 'pass',
'database' => $this->db['global']->get_db_name($loggedInUserId);
...etc
);
Hopefully that makes sense - I need to get the db name based on the logged in user. Obviously I need to build either a Model or just a function to grab it, but the question is where? Do I add a model, connect to the global db, and then load the model in the database config? Is there some other, easier, more productive way to do this, or is that it? Will the codeigniter core files be able to be called from inside the codeigniter config files?
Use 2 database connections. 1 for the global user accounts and 1 for the actual user database. Then create a helper function to grab the user databases. Just an idea.

Running migrations while changing database

I'm making a multi tenancy application. For reasons I've chosen to go with a database for each of the tenants, and then a "master" database which contains meta information about the different tenants, and such.
I've therefore grouped my migrations into two directories:
Master - which contains the migrations for the master database.
Tenants - contains the migrations for each tenant database.
Instead of having to specify the path to the migration folders and the database to run on, each time I migrate, I've created a console command instead. However this is where the issue occurs.
I handle tenants using the subdomain as an identifier for which database to load from, using a middleware like this:
public function handle($request, Closure $next)
{
$domains = explode('.', parse_url($request->url())['host']);
if (count($domains) < 3)
return app()->abort(403, "A valid subdomain is required");
\Config::set('database.connections.tenant.database', $domains[0]);
return $next($request);
}
This works fine for web.
However when I use Config::set() within my console command, it's being ignored, and Laravel is just using the one from my .env file.
database config file:
return [
'default' => env('DB_CONNECTION', 'tenant'),
'connections' => [
'tenant' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_TENANT_DATABASE'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', '')
],
'master' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_MASTER_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
],
]
];
(I've cleaned it up a bit, so only the essential is shown).
In my .env file I've then specified a default tenant database, which is used when I'm using the cli.
DB_HOST=127.0.0.1
DB_MASTER_DATABASE=master
DB_TENANT_DATABASE=company
DB_USERNAME=root
DB_PASSWORD=
Within my TenantMigrater I iterate through each tenant, and run migrate for each of them with a different connection and path.
foreach(Tenant::all() as $tenant)
{
$this->info("Running migrations for the tenant: {$tenant->name}");
\Config::set('database.connections.tenant.database', $tenant->database);
$this->call('migrate', [
'--database' => 'tenant',
'--path' => 'database/migrations/tenants/'
]);
}
Although I'm setting a new database for the tenant connection, it's still falling back to the one specified in the .env file.
I tried going through Laravel's migrater, and as far I could see, the name was being set in the config correctly, so I'm feeling a bit confused. Any ideas?
Edit:
I think I've gotten one step closer to the issue. It seems like, when running php artisan *, the cli starts a connection to the database under the name specified in the config/database.php file. When i then try to override this, the connection is already open to the connection (or so laravel thinks), and it just hand my command the same connection, without setting the new database, hence why it keeps using the same database. However, I have no idea as to how to force it to create a new connection each time I iterate through the tenant.
Running \DB::reconnect('tenant'); before each migration seemed to make it work. This is a bit counter intuitive I think though.

Migrating existing cakephp 3.0 database to postgres from mysql

I am in the process of migrating a cakephp 3.0 database from mysql to postgress. I used this tool for the database migration and it worked beautifully. After that I changed the config file as shown below.
'default' => [
'className' => 'Cake\Database\Connection',
'driver' => 'Cake\Database\Driver\Postgres',
'persistent' => false,
'host' => 'localhost',
'port' => '5432',
'username' => 'postgres',
'password' => 'mypass',
'database' => 'cake_bookmarks',
'encoding' => 'utf8',
'timezone' => 'UTC',
'cacheMetadata' => true,
'log' => false,
'quoteIdentifiers' => false,
//'init' => ['SET GLOBAL innodb_stats_on_metadata = 0'],
],
The root folder in localhost also shows "successfully connected to database". However when i run my application, it shows an error:
Cannot describe mytable. It has 0 columns. Cake\Database\Exception
I can't make sure if this is because of not connecting to the database (which i think is unlikely as the root page shows as connected) or cakephp being unable to use my database.
If so, how can I fix the issue. I am quite new to cakephp too, just confguring and doing basic stuff.
Try the following (test after each step):
Check if the table is present in the database
Check if the expected columns are defined into the table
Clear the Cake cache (if is FileCache is enough to delete files under tmp/cache/persistent tmp/cache/models and tmp/cache/views
Check the permissions of the specific user on the database cake_bookmarks (maybe via phppgadmin)
Hope to help!

Laravel 5 Eloquent charset utf8 issues

I use Laravel 5.1 and a mysql server.
I have a database with table in utf8 unicode, and my databse configuration file is like this :
'mysql' => array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'database',
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => 'false',
),
But when I use queries from eloquent, my texts which have accents are broken. It's not a problem from blade because I can write accent in the views correctly, and if I use PDO directly my text is nice.
How can I solve my problem with my queries from eloquent ?
I found my problem, I hope it will help others :
My Mysql databases are encoded in latin1 by default. I was sure that my databases were in utf8 so I configured as that in the configuration file on my laravel project.

Categories