Deploying someone else's Laravel project (mysql connection issue) - php

I'm new to this business. I use ubuntu and homestead, downloaded the project and dump dump, there was no env configuration file in the folder., I took env from a clean project and entered my settings, then I ran vagrant up, vagrant ssh, went into the project folder and tried to simply execute php artisan as a result, I get this kind of message:
"In Connection.php line 664:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'xxxx_db.newsletter_settings' doesn't exist (SQL: select * from newsletter_settings limit 1)"
where "xxxx_db" is the database that I entered into env, and "newsletter_settings" is taken as I understood from app / Eloquent / NewsletterSettings
from the lines:
class NewsletterSetting extends Model
{
use Notifiable;
protected $table = 'newsletter_settings';
protected $primaryKey = 'id';
/**
My dear connoisseurs question: how can I tie up the project correctly?
I tried to comment out and temporarily delete the file from which the protected $ table = 'newsletter_settings' is taken;
but nothing worked.
For earlier I apologize for my english

Create Database
change db name as below
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourdbname
DB_USERNAME=root
DB_PASSWORD=
Run command php artisan migrate

Step 1 Artisan Cached Config Files
Try to run php artisan optimize:clear, this will clear all of your cached config files and mean any changes you make to your config files will take effect immediately.
Step 2 Manual Cached Config Files
If you cannot even run php artisan to clear the cache, you can delete them manually by removing the files within bootstrap/cache. (Keep the git ignore)
Step 3 Code Review
If the cache has no effect, then it may be that you have database calls somewhere within a boot method on one of your classes. The boot methods all run before the content of php artisan would have returned. It is not uncommon for developers who don't frequently delete their databases to fall into this trap as it won't manifest itself until someone tries to install the project from scratch.

1.Create Database
2.set database name and credentials in .env
3.Run command php artisan migrate

Thank you all, found in a separate Kernel.php this kind of string:
$setting = NewsletterSetting::first();
if(!empty($setting)) {
$schedule->command('command:newsletter')
->withoutOverlapping()
->days($setting['weekdays'])
->at($setting->send_time);
}

Related

Laravel keeps connecting to old database connection

Context :
I have DB1 and DB2 and a laravel application using DB1 so far
I want now that laravel (8) application to use DB2 instead (both DB1 & 2 are mysql)
I edited the .env file to change the DB_HOST and cleared the config cache
Expected : Laravel using DB2
Problem : Laravel still connects to DB1
Things I've tried :
php artisan config:cache / clear
php artisan optimize:clear
restarted DB1/DB2
restarted nginx
restarted php-fpm
redeployed the whole app (with composer install etc.)
tried adding a new connection in config/database.php instead of editing the existing one : same issue
hardcoding the values in config/database.php instead of referencing the env file : same issue
php artisan db sql --> connects to the RIGHT DB (this is what's driving me insane)
... but php artisan tinker doesn't seem to. I created a dummy table in DB2 only (so not present in DB1) and getting that table with \DB::connection('mysql')->table('dummy')->get(); shows an error via tinker
obviously, stopping DB1 makes the application go offline ("No such file or directory" blabla ie. no database PDO)
I don't even know what to try anymore. Every post somewhat related online are solved after a simple artisan config:clear/cache ....
Any thoughts appreciated ?
The answer was DB_SOCKET=/tmp/mysql.sock in my .env file that locked the connection to the previous (local) DB. Removing that from my env file solved the issue
to change the database you need to write the database name on DB_DATABASE instead on DB_HOST...

How to run laravel migrations without artisan (using code)

I recently hosted a laravel project (for a customer) on shared hosting, after failed attempts to get access to the server via ssh I contacted the host who informed me that ssh service was not available for my customers hosting plan, that means I have no access to terminal and can't use artisan. I know how to write a php script that will create sql tables but just before that I was wondering if theres a shortcut to this with laravel since the migrations(tables) are already defined. What I want is like to create a route project.com/run_migrations to do the job! Thanks in advance
You can easily create a small Artisan script within PHP like this:
Artisan::call('migrate');
This equals php artisan migrate. Use it anywhere you want to run your migrations.
If you are in production mode (if APP_ENV=production inside your .env file) then you would have to force the migration in case you want to allow to make changes. You can do it as follows:
Artisan::call('migrate', ["--force" => true ]);
This equals adding the --force flag a la php artisan migrate --force.
To answer your specific question though, create a route like this:
Route::get('/run-migrations', function () {
return Artisan::call('migrate', ["--force" => true ]);
});
If you are interested in creating a web installer, you might be interested in this package:
https://github.com/Froiden/laravel-installer
Check out the code to see how he handles migrations and seeds etc.

Php artisan not working because i deleted the table in phpMyadmin , how to undo this?

I deleted a table directly in my phpMyAdmin and how when i run the command php artsan migrate:rollback , i get the following error:
Failed to open:stream: No such file or directory.
I already deleted the migration file from the migrations folder , so why am i getting this error ??
I was just going through the laravel migrations documentation HERE, and i saw the below command:
php artisan migrate:rollback --step=5
So i tried the below in my command line:
php artisan migrate:rollback --step=1
To rollback my last migration , but it does't seem to work. Thats the reason i deleted the table directly in the phpMyAdmin.
Below is the error i get now , when i run the php artsan migrate:rollback:
Please try the following commands, it will be fine.
To clear cache
php artisan cache:clear
To composer autoload
composer dump-autoload
Now restart your Laravel server and it will be fine.
It will be working by now. However, it is never recommended to delete a table and a migration file directly. If that's the case, Laravel wouldn't have used migration at all. Please take care next time.
Since you removed the file before rolling back, I would suggest to delete the entry manually from your migrations table.
Search for the full name and delete just the 1 entry.
DELETE FROM `migrations` where `name` = '[2017_01_09_xxx]';
However, if your migration was already committed and pushed to remote and other people are working on the same codebase, I would suggest restoring the table on your local env and also restore the migration file with that name and remove the table by adding a new migration.
This flow will make sure that when other people work with your changes or that when you deploy and run migrations, you are able to do so without issues.

Laravel Artisan - reload .env variables or restart framework

I'm trying to write a command as a quickstart to build a project. The command asks for input for database details and then changes the .env file. The problem is that the command needs to do some Database queries afterwards, but the .env variables are not reloaded.
My question would be, is there a way to reload or override .env variables runtime. And if not, is there a way to call another Artisan command freshly, so framework bootstraps again?
In my command I tried doing $this->call('build:project') in my actual command, but even in the second call the variables are not reloaded.
Is there a way to achieve this without making the user manually call multiple commands?
Thanks!
i had the same problem with reloaded .env variables, and i fixed it with this command line which allow you to clear the configuration :
php artisan config:clear
Hope that helped. Regards.
Laravel uses config files which take data from .env file. So, what you can do is to override configuration values at runtime:
config(['database.default' => 'mysql']);
Try to clear cache it helped me (couldn't ssh into the server)
Is there a {app route}/bootstrap/cache/config.php file on the production server? Delete it.
This helped me
As OP I'm trying to bootstrap a Laravel project build by running console command and asking for the database credentials in the middle of the process.
This is a tricky problem and nothing I read was able to fix it : reset config, cache, Dotenv reload, etc... It seems that once the console command / operation is initialized the initial database connection is kept all over until the end.
The working solution I found is to bypass, after database modification are done, this cached state by using native shell exec command and passing the php artisan command as parameter :
passthru('php artisan migrate');
So, the order will be :
php artisan project:build (or whatever is your console command)
prompt the user for database credentials
replace values in .env file (your search & replace algorythm)
run php artisan config:cache
passthru('php artisan migrate'); ro run your migrations
shell_exec would do the same but in silent mode while passthru will return the output generated by console.
https://www.php.net/manual/en/function.passthru.php
Done successfully on Laravel 8.52

Reloading .env variables without restarting server (Laravel 5, shared hosting)

My Laravel 5 has run OK until the database was configured, then found this error:
SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
Doing some research it seems that I configured MySQL access too late, so I should restart the server in order to get the correct environment variables. Well, I'm using Dreamhost's shared server and I just can't do that.
How should I fix this issue?
Thanks
If you have run php artisan config:cache on your server, then your Laravel app could cache outdated config settings that you've put in the .env file.
Run php artisan config:clear to fix that.
I know this is old, but for local dev, this is what got things back to a production .env file:
rm bootstrap/cache/config.php
then
php artisan config:cache
php artisan config:clear
php artisan cache:clear
It's possible that your configuration variables are cached. Verify your config/app.php as well as your .env file then try
php artisan cache:clear
on the command line.
To be clear there are 4 types of caches you can clear depending upon your case.
php artisan cache:clear
You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.
php artisan route:cache
This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.
php artisan config:cache
This will clear the caching of the env file and reload it
php artisan view:clear
This will clear the compiled view files of your application.
For Shared Hosting
Most of the shared hosting providers don't provide SSH access to the systems. In such a case you will need to create a route and call the following line as below:
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "All cache cleared";
});
A short solution:
use Dotenv;
with(new Dotenv(app()->environmentPath(), app()->environmentFile()))->overload();
with(new LoadConfiguration())->bootstrap(app());
In my case I needed to re-establish database connection after altering .env programmatically, but it didn't work , If you get into this trouble try this
app('db')->purge($connection->getName());
after reloading .env , that's because Laravel App could have accessed the default connection before and the \Illuminate\Database\DatabaseManager needs to re-read config parameters.
In case anybody stumbles upon this question who cannot reload their webserver (long running console command like a queue runner) or needs to reload their .env file mid-request, i found a way to properly reload .env variables in laravel 5.
use Dotenv;
use InvalidArgumentException;
try {
Dotenv::makeMutable();
Dotenv::load(app()->environmentPath(), app()->environmentFile());
Dotenv::makeImmutable();
} catch (InvalidArgumentException $e) {
//
}
This is the only question I could find relating to reloading .env and thus config($key) values on an existing app instance, but many of these answers should probably live on a different question.
I got the following to work for a Laravel 6.x application, while trying to make an artisan command use my cypress environment variables.
For context $this->laravel === app().
/**
* Make the application use the cypress environment variables
*
* #return void
*/
protected function enableCypressEnv()
{
// Get all of the original values from config. We need to do this because
// rebuilding config will skip packages.
$old = app(Repository::class)->all();
// Change the applications env file
$this->laravel->loadEnvironmentFrom('.env.cypress');
// Reload the app's environment variables
Dotenv::create(
$this->laravel->environmentPath(),
$this->laravel->environmentFile(),
Env::getFactory()
)->overload();
// Force config to be rebuitl with new env
(new LoadConfiguration())->bootstrap($this->laravel);
// Get all of the new values from buidling with new env
$new = app(Repository::class)->all();
// Merge the new values over the old distinctly
$merged = array_merge_recursive_distinct($old, $new);
// Get the applications configuration instance
$config = config();
// Overwrite all of the values in the container in accordance with the merged values
foreach ($merged as $key => $value) {
$config->set([$key => $value]);
}
}
Shoutout to the answers above for pointing me in the right direction, but I will include my answer here as none of them worked perfectly for me.
In config/database.php I changed the default DB connection from mysql to sqlite. I deleted the .env file (actually renamed it) and created the sqlite file with touch storage/database.sqlite. The migration worked with sqlite.
Then I switched back the config/database.php default DB connection to mysql and recovered the .env file. The migration worked with mysql.
It doesn't make sense I guess. Maybe was something serverside.

Categories