how to run php laravel artisan commands from web - php

How could Laravel Artisan commands be executed on the server by sending the command as a query parameter in an URL?

Without commencing new dockerfile you cant run laravel artisan commands if those need mysql connection command line. If you are searching for quick and dirty hack here it is:
In order to work on existing php-fpm-alpine, use artisan commands from the web interface those code can be added to index.php (generally located in /public directory)
if($debugmode)
if(#$_REQUEST['artisan']){
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$vars = explode(' ', $_REQUEST['artisan']);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArrayInput($vars),
new Symfony\Component\Console\Output\ConsoleOutput
);
return '';
}
those shoud come between
$app = require_once __DIR__.'/bootstrap/app.php';
and
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);
usage http://localhost/?artisan=vendor:publish

Related

Symfony - use Command to run Phing task

When I try to run that phing command: bin/phing clear_cache_action from a console, everything works. Unfortunately, when I try to run the same command from the controller in the Symfony project I get an error.
That my code:
public function clearAction()
{
$process = new Process('bin/phing clear_cache_action');
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();
}
Symfony returns me that error:
The command "bin/phing clear_cache_action" failed.
Exit Code: 127(Command not found)
Working directory: /var/www/caolin/web
Output:
================
Error Output:
================
sh: 1: bin/phing: not found
Linux commands e.g. 'ls' works properly.
How can I run phing command from code?
I guess you are trying to execute phing from a Controller. Thus Working directory: /var/www/caolin/web instead of /var/www/caolin causes resolving bin/phing to /var/www/caolin/web/bin/phing which does not exist. You should set your current working directory to %kernel.project_dir%:
$process = new Process(
['bin/phing', 'clear_cache_action'],
$this->getParameter('kernel.project_dir')
);
$process->run();
However, I would not recommend starting a process from a Controller unless you are really sure what you are doing.

Symfony/Process cant run sh script from directory

I have some script: /home/user/project/deploy.sh
I trying to run with Symfony/Process component from php handler in another directory:
$process = new Process(['./deploy.sh']);
$process->setWorkingDirectory('/home/user/project');
$process->run(function ($type, $buffer) {
echo $buffer;
});
But I got an error:
The provided cwd "/home/user/project" does not exist.
This folder exists and symfony handler ran as correct user which have correct permissions to this folder. What is the correct way to run this script from another folder?
Just for debugging purposes test code below.
$process = new Process(['/home/user/project/bin/console', '--version']);
$process->run();
if (!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
echo $process->getOutput();
If it does work then try:
new Process(['/home/user/project/deploy.sh']);
new Process(['sh /home/user/project/deploy.sh']);
Process::fromShellCommandline('/home/user/project/deploy.sh');
You may need to use the full path to sh since the webserver uses a different user and a PATH variable.

Ignore a custom Laravel Artisan command on production

I've written a custom Artisan command (let's call it MyDusk.php) that expands/abstracts some of the functionality of the core Dusk command.
This custom command extends Laravel\Dusk\Console\DuskCommand from within the Dusk package.
The problem is, on production the Dusk package is not installed (it's under require-dev in composer.json)
So when composer is generating its autoload files on production, it errors out when it gets to MyDusk.php because it can't find Laravel\Dusk\Console\DuskCommand.
PHP Fatal error: Class 'Laravel\Dusk\Console\DuskCommand' not found in app/Console/Commands/Dusk.php on line 10
In Dusk.php line 10:
Class 'Laravel\Dusk\Console\DuskCommand' not found
I tried moving the Dusk package to require so it would be available on production (not ideal, I know), but there's a line in the core Dusk service provider that throws an exception when it's run on production preventing this:
# From: vendor/laravel/dusk/src/DuskServiceProvider.php
if ($this->app->environment('production')) {
throw new Exception('It is unsafe to run Dusk in production.');
}
I'm trying to think of the most elegant solution to allow for my custom Dusk command to be part of the application and accessible locally, without throwing errors on production.
One idea: Write my Dusk command as its own package, that's also only in require-dev.
Any other ideas?
I just took a look at the API, you could do this:
You could move your command to App\Console\Commmands\Local\DuskCommand.php.
By default, if you check the commands() method in the Kernel, it's only going to load commands found in App\Console\Commands. This will not include the sub-directories.
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
This is the default commands() method. You could switch this implementation to the one below:
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$paths = [
__DIR__ . '/Commands'
];
if(app()->environment('local')) {
$paths[] = __DIR__ . '/Commands/Local';
}
$this->load($paths);
require base_path('routes/console.php');
}
So, in local, we are also going to load commands based in App\Console\Commands\Local.
Admittedly, I didn't give this a try myself, but I am assuming that it should work.
Edit: I gave it a try and it seems to be working just fine. I thought, I'd try to explain it a bit more. Basically, after doing a composer dump-autoload, Laravel is listening to this event and doing two things:
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"#php artisan package:discover --ansi"
]
The second one is trying to run the Auto-Package Discovery command and this is where it will fail. The Artisan executable actually boots the application with the Console Kernel.
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
While resolving the Kernel, it will also try to boot up the Commands that it needs so that they are available to Artisan, and this is where it fails.
However, like I mentioned above, if you only boot the Commands you need in production, this issue won't happen.
Accepted answer seems not to work in Laravel 6. This worked for me:
Create your command with php artisan make:command YourCommand and move it to app/Console/Local.
Change its namespace to App\Console\Local.
Then, in app/Console/Kernel.php:
protected function commands()
{
$paths = [
__DIR__ . '/Commands'
];
if(app()->environment('local')) {
$paths[] = __DIR__ . '/Local';
}
$this->load($paths);
require base_path('routes/console.php');
}
Enjoy ;)

composer install pass command line argument or parameter to bin/console

I'm trying to make my symfony 3.0 app capable to work with multiple kernel.
real aim : Multiple applications in one project
Generally everything is OK. I edited bin/console it's content exactly as the following. It works exactly and results what I need via php bin/console --app=api
But when I execute composer install bin/console throws the Exception naturally it doesn't knows about --app parameter. I want to make something like composer install --app=api and desired behaviour it would pass the parameter to bin/console I checked documentation and almost every pixel of the internet couldn't find a solution.
#!/usr/bin/env php
<?php
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Debug\Debug;
// if you don't want to setup permissions the proper way, just uncomment the following PHP line
// read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information
//umask(0000);
set_time_limit(0);
/**
* #var Composer\Autoload\ClassLoader $loader
*/
$loader = require __DIR__.'/../apps/autoload.php';
$input = new ArgvInput();
$env = $input->getParameterOption(array('--env', '-e'), getenv('SYMFONY_ENV') ?: 'dev');
$app = $input->getParameterOption(array('--app', '-a'));
$debug = getenv('SYMFONY_DEBUG') !== '0' && !$input->hasParameterOption(array('--no-debug', '')) && $env !== 'prod';
if ($debug) {
Debug::enable();
}
switch ($app) {
case 'api':
$kernel = new ApiKernel($env, $debug);
break;
case 'frontend':
$kernel = new FrontendKernel($env, $debug);
break;
default:
throw new \InvalidArgumentException("[--app|-a=<app>] app: api|frontend");
break;
}
$application = new Application($kernel);
$application->getDefinition()->addOptions([
new InputOption('--app', '-a', InputOption::VALUE_REQUIRED, 'The application to operate in.'),
]);
$application->run($input);
You can use composer install --no-scripts to prevent automatically running app/console after installation.
Or you can remove the the bin/console commands from the scripts section in your composer.json altogether, which probably makes more sense. See https://github.com/symfony/symfony-standard/blob/master/composer.json#L33-L34
Or you can use environment variables instead of arguments.

Laravel running migrations on "app/database/migrations" folder recursively

So my migrations folder looks like this since I have dozens of tables it keeps things organized and clean:
migrations/
create_user_table.php
relations/
translations/
I'm trying to do a refresh all migrations and seed but it seems like I've run into a slight hiccup where I don't know the artisan command to run migrations recursively (i.e. run migrations in the relations and translations folders as well).
I've tried adding --path="app/database/migrations/*" however it spat out an error. Does anyone know the solution to this?
The only way to do it right now is to manually go through all the migrations. That is, you have to run the migration command on each of your subfolders:
php artisan migrate --path=/app/database/migrations/relations
php artisan migrate --path=/app/database/migrations/translations
However, what you can do is easily extend the artisan system to write your own migrate command that will iterate through all folders under the migrations folder, create these commands for you and run them.
You can also simply write a shell script if you don't want to get into doing this via artisan
Edit: for Laravel >= 5.0, the correct commands to migrate migration files in sub directories would be:
php artisan migrate --path=/database/migrations/relations
php artisan migrate --path=/database/migrations/translations
This add to boot method in AppServiceProvider
$mainPath = database_path('migrations');
$directories = glob($mainPath . '/*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);
$this->loadMigrationsFrom($paths);
Now you use can php artisan migrate and also php artisan migrate:back
You can also use a wildcard, like so:
php artisan migrate --path=/database/migrations/*
You can use the following command to do this recursively:
php artisan migrate --path=/database/migrations/**/*
**/* is also known as the globstar
Before this works you must check if your bash supports the globstar.
You can do this by executing shopt and checking for globstar.
Globstar is supported by default by most server distributions but might not work on MAC.
For more on globstar see: https://www.linuxjournal.com/content/globstar-new-bash-globbing-option
In Laravel 5 the database folder sits alongside the app folder by default. So you could run this to migrate a single folders migrations:
php artisan migrate --path=/database/migrations/users
You can try this package nscreed/laravel-migration-paths. By default all sub directories inside the migrations folder will be autoloaded. Even you can add any directories very easily.
'paths' => [
database_path('migrations'),
'path/to/custom_migrations', // Your Custom Migration Directory
],
Don't need any special command just the generic: php artisan migrate will do your tasks.
I rewrote the MigrationServiceProvider:
- registerResetCommand()
- registerStatusCommand()
- registerMigrateCommand()
There you can register your own commands:
class MigrateCommand extends Illuminate\Database\Console\Migrations\MigrateCommand
After that you just need to extend youd directories:
protected function getMigrationPaths()
Or you just register the paths on application boot.
I've already done my solution before I knwewd about '$this->loadMigrationsFrom'.
A Simple solution is to create an Artisan Command for example (migrate:all),
then inside handle function define migrate command for each sub directories as mentioned bellow.
Artisan::call('migrate', [
'--path' => '/database/migrations/employee'
]);
Only relative path works for me (in Laravel 5.7):
php artisan migrate --path=database/migrations/your-folder-with-migrations
This works at laravel 8
php artisan migrate --path=database/migrations/tenant
It is a not a "direct" solution but i suggest you to look at Modularity into your laravel project.
Modules can segment your application in several smaller "folders" and bring migration, seeds, classes, routes, controllers, commands together in easily maintainable folders.
This package is a good start : https://github.com/pingpong-labs/modules
No changes are necessary, whenever you need it, use this command:
php artisan migrate --path=database/migrations/*
If you want a shortcut, you can include that in your composer.json:
"scripts": {
"migrate": [
"#php artisan migrate --force --path=database/migrations/*"
]
}
Then just use composer migrate in the terminal.
add in app/Providers/AppServiceProvider.php the path of your migration folder, you can add a string or an array
public function register()
{
$this->registerMigrations();
}
protected function registerMigrations()
{
return $this->loadMigrationsFrom(__DIR__ . '/../../database/migrations/**/*');
}
A Simple Laravel solution is to create a gulp task (say migrate-others).
var elixir = require('laravel-elixir');
var gulp = require('gulp');
var shell = require('gulp-shell')
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Sass
| file for our application, as well as publishing vendor resources.
|
*/
elixir(function(mix) {
mix.sass('app.scss');
});
// Our Task
gulp.task('migrate-others', shell.task([
'php artisan migrate --path=/app/database/migrations/relations',
'php artisan migrate --path=/app/database/migrations/translations',
]));
Now you can simply call
gulp migrate-others
Here you go!
function rei($folder)
{
$iterator = new DirectoryIterator($folder);
system("php artisan migrate --path=" . $folder);
foreach ($iterator as $fileinfo) {
if ($fileinfo->isDir() && !$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
rei($folder . $fileinfo->getFilename() . '/');
}
}
}
rei('./database/');

Categories