How to run laravel migrations without artisan (using code) - php

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.

Related

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

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);
}

Laravel - Catch php artisan commands

I've did some changes in my config/app to use multiple databases selected by front-end,
now I have to tell in \Request()->header('database') which database I want access.
It's work perfectly, the problem is: when I try to do any artisan commands my logic dies, because isn't informed the database.
So I need to inform the database in artisan commands, like that:
php artisan migrate --database=sandiego_school
php artisan migrate:rollback --database=newyork_school
How can I observer all commands to get the argument?
In this case I guess you should create your own commands that overrides the commands you want to call, then in the handle method of the command you could specify the connexion you want to work on:
\DB::setDefaultConnection($connexion);
or also you can simply add header to request:
request()->headers->set('database', $dbname)

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.

Laravel migration cancelled

when I trying to migrate something I get this error:
**************************************
* Application In Production! *
**************************************
Do you really wish to run this command?
Command Cancelled!
Im running a centOS 6.5 server without Plesk 12
Is there anyway to figure out what the error is or how to solve it?
Thanks
A bit late for answer but just for info purpose you can use php artisan migrate --force to avoid it OR in laravel 5.2 they are using a key env in config/app.php configure it to avoid this prompt
reference https://github.com/laravel/laravel/blob/master/config/app.php
Just use --force flag in production:
php artisan migrate --force
https://laravel.com/docs/6.x/migrations#running-migrations
Forcing Migrations To Run In Production
Some migration operations are destructive, which means they may cause
you to lose data. In order to protect you from running these commands
against your production database, you will be prompted for
confirmation before the commands are executed. To force the commands
to run without a prompt, use the --force flag.
Change your environment first from production to local . /bootstrap/start.php somewhere line no 26
$env = $app->detectEnvironment(array(
// find your machine name and replace mine
'local' => array('hassanjamal.local'),
));
I've just bumped into this problem as well. If you don't want to reconfigure your app (which is probably a good idea) hit 'Y' and then enter instead of just enter. It will go on even in production setting.
Simple,
$env = $app->detectEnvironment(function()
{
return 'development';
});
Good luck!

Categories