Ignore a custom Laravel Artisan command on production - php

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

Related

Kernel does not exist in laravel

I have already developed project in laravel and i'm setting up it in my local computer but after running php artisan serve i'm getting this error
PHP Fatal error: Uncaught ReflectionException: Class App\Console\Kernel does not exist in C:\xampp\htdocs\translate\vendor\laravel\framework\src\Illuminate\Container\Container.php:788
I don't know what is wrong but I have tried everything that I have found on internet
composer update
composer dump-autoload
composer self-update
php artisan config:clear
php artisan cache:clear
none of that command worked for me
You must run composer install for installing the new dependencies.
Since you mentioned that you have issues with your other artisan commands delete everything inside the bootstrap->cache folder, except of the .gitignore file of course, manually and then run php artisan optimize
That way your "corrupted" cache will be recreated and reconfigured.
First thing you must do is to make sure your artisan commands are working right, so do the caching fix i suggest first. Then you can run the composer commands you mentioned also in your question.
Check you have this file in app/Console folder
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* #var array
*/
protected $commands = [
//
];
/**
* Define the application's command schedule.
*
* #param \Illuminate\Console\Scheduling\Schedule $schedule
* #return void
*/
protected function schedule(Schedule $schedule)
{
/*$schedule->command('users:update')->everyMinute();
$schedule->command('servers:update')->everyMinute();*/
}
/**
* Register the commands for the application.
*
* #return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

Laravel console command trait method not found

I have a Laravel project that has been deployed with Forge and had OPCache enabled using Forge. I noticed last week that when I pushed some changes, the changes that were in the views and in the controllers were present on the server, but custom artisan commands that I run don't recognize updates.
Put another way, updates to the blades are showing on the screen. Updates that I have added to the controllers are changing the way information is passed to the blade files, but I have a custom artisan command that runs a series of methods in a trait. The actual file on the server shows the new method that I pushed, but when I run the artisan command in the CLI, it says that the method cannot be found.
I have stopped, restarted, and reloaded OPCache countless times. I have restarted Nginx. I have disabled OPCache and restarted PHP. It is still saying that the method is not found. Does anyone have any ideas?
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Traits\FTPImportsTrait;
class CheckFTPImports extends Command
{
use FTPImportsTrait;
protected $signature = 'checkForImports';
protected $description = 'Check for imports...';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$this->checkBankImports();
}
}
-----------
<?php
namespace App\Traits;
trait FTPImportsTrait;
{
public function checkBankImports()
{
dd('YOU ARE NOT CRAZY');
}
}
$ php artisan checkForImports
$ method checkBankImports does not exist.
UPDATE:
It has to be some sort of configuration issue on the server. I just deployed the project to a fresh DO droplet and the command works as expected.
It only happened in the production environment for me.
Running:
php artisan clear-compiled
deleted the cached version and solved my issue.
Thanks a ton to #num8er.

Script #php artisan package:discover handling the post-autoload-dump event returned with error code 255

I moved my project from desk to another.
When I run php artisan it does not work.
I tried to run composer update, but it returns the error
Script #php artisan package:discover handling the post-autoload-dump event returned with error code 255
This is how I solved this after an upgrade from laravel version 6.x - 7.x:
In App\Exceptions\Handler changed
//Use Exception;
Use Throwable;
Then methods to accept instances of Throwable instead of Exceptions as follows:
//public function report(Exception$exception);
public function report(Throwable $exception);
//public function render($request, Exception $exception);
public function render($request, Throwable $exception);
In config\session.php:
//'secure' => env('SESSION_SECURE_COOKIE', false),
'secure' => env('SESSION_SECURE_COOKIE', null),
Then run composer update
I solved the problem this way:
cd bootstrap/cache/
rm -rf *.php
The bootstrap directory contains the app.php file that initializes the structure. This directory also houses a cache directory that contains structure-generated files for performance optimization, such as files and route cache services. Laravel stores configuration files, provider, and cached services to optimize the fetching of this information. The problem with me was when the other developer ran the 'php artisan config: cache' command on your machine and since the cache folder contains files that can be deleted, I deleted them and solved the problem.
If this happened after Laravel update from 6.x to 7.x, then this could be due to the update of Symfony. See the upgrade guide of this part:
https://laravel.com/docs/7.x/upgrade#symfony-5-related-upgrades
I was upgrading my Laravel from 5.8 to 8.0 and I got this error.
So my fixes were
As #nobuhiroharada mentioned that I had missed .env file in my project
Second is that Laravel removed Exception and replaced it with Throwable. So we need to fix that in our app\Exceptions\Handler.php. One can refer Medium.com for the error fix.
In the upgrade guide of Laravel 8.x you need to update the dependencies like this
Next, in your composer.json file, remove classmap block from the autoload section and add the new namespaced class directory mappings:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
Finally from bootstrap\cache delete the cache files and run composer update.
These 5 steps might help you remove the error you are facing in your Laravel Project.
This happens because you have upgraded to Laravel 7.
To fix it, update app/Exceptions/Handler.php like so:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable; // <-- ADD THIS
class Handler extends ExceptionHandler
{
public function report(Throwable $exception) // <-- USE Throwable HERE
{
parent::report($exception);
}
public function render($request, Throwable $exception) // AND HERE
{
return parent::render($request, $exception);
}
}
This is documented in the official upgrade guide here:
https://laravel.com/docs/7.x/upgrade#symfony-5-related-upgrades
I got the same problem in Win 8 and solve it:
Here is the steps.
Step-1: Go to your project directory
Step-2: And type command cd bootstrap/cache/
Step-3: Again type command del -rf *.php
Step-4: Update your composer composer update
Step-5: Now you are done: php artisan serve
Thanks.
Do you have .env file in your new project?
I had same error message. When I add .env file, error is gone.
success message like this.
Generating optimized autoload files
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover
Discovered Package: fideloper/proxy
Discovered Package: ixudra/curl
Discovered Package: laravel/tinker
Discovered Package: nesbot/carbon
Discovered Package: socialiteproviders/manager
Package manifest generated successfully.
I hope this will help you.
maybe you have an error in the project code (for example, in routes or controller). This may be one of the reasons for this error.
In my project, the web.php file has a syntax error. I defined this when I started the php artisan command
C:\OSPanel\domains\lara.shop.loc>php artisan
In web.php line
syntax error, unexpected end of file
Same issue when I update laravel from 6.x to 7.x
I tried the most voted answer but it didn't work, then I used php artisan serve I noticed that:
RuntimeException
In order to use the Auth::routes() method, please install the laravel/ui package.
Try composer require laravel/ui maybe it will work.
I solve this error by deleting the vendor table then run composer update. I'm using Laravel 7. So, if you are not updating from the older Laravel version, maybe this is the solution.
I had this same problem when running composer update in a Laravel project. In the package.json it's configured to run artisan package:discover, which failed with:
Class 'Symfony\Component\Translation\Translator' not found in vendor/nesbot/carbon/src/Carbon/Translator.php on line 18
When I looked in the vendor/symfony/translation directory I found that it was completely empty, which explained the error.
The solution was to completely delete the vendor directory and then re-run composer update. This was the only way that I was able to make composer install the missing files.
I deleted composer.lock file and ran composer update.
That solved mine
I had the same issue, my problem was the PHP version of the server account did not match my Docker container. The SSH terminal was using the global php version for the server.
php -v
Confirm it's the version your project needs.
Composer did warn me that a higher php version was required but I rm -rf'd /vendor and ./composer.lock without paying too much attention to the warnings!
Got the same problem.
php artisan doesn't work.
composer install got error:
Script #php artisan package:discover handling the post-autoload-dump event returned with error code 255
And this works for me.
When I switch another linux user. It works.
some files are owned by another linux user.
So I use root account and change all the project file to the specific user,
chown -R www:www project/
and use that user to execute composer cmd
and then it works.
My case/solution, in case it helps anyone...
I copied my repo over from my old Windows computer to a new one, and installed the latest php.
composer install was returning:
Root composer.json requires php ^7.1.3 but your php version (8.1.10) does not satisfy that requirement
...which I thought was odd (assuming 8 satisfied ^7), so I continued on with composer install --ignore-platform-reqs, and ended up with this particular issue.
After trying a bunch of other possible solutions, what ended up working for me was simply downgrading to the same PHP version from my old machine (7.4.33).
This is not an actual error. If you look a bit above you'll see the actual error.
In my case, there was an error in my code:
PHP Fatal error: Declaration of
App\Exceptions\Handler::render($request, App\Exceptions\Exception $exception)
must be compatible with
Illuminate\Foundation\Exceptions\Handler::render($request, Throwable $e)
It is not possible to tell you what is actually a problem in your code, so you have to look real reason for this error in your stack trace.
In my case there is missing folder and its file Kernel.php in
app/Console
So I created app/Console/Kernel.php using code from previous project.
Now everything working fine.
Make sure your config\constants.php (and/or resources\lang\en\local.php) has no syntax errors. I get this error a lot by missing commas in constants.php file.
If you have this error the simplest way is you can try using composer install instead of composer update
I deleted my project I created a new folder and cloned the repository again and after that I gave composer install / update.
I got the same problem in Win 10 and solve it:
Here is the steps.
Step-1: Go to your project directory
Step-2: Update your composer
composer update
Step-3: Now you are done: php artisan serve
Nothing worked, so I installed a new project, and I read Handler.php in App\Exceptions, it was different, probably because I copied some solution and Internet and deleted the following:
protected $dontReport = [
//
];
protected $dontFlash = [
'password',
'password_confirmation',
];
I copy here all of Handler.php generated by laravel 7.5, may be useful for someone:
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that are not reported.
*
* #var array
*/
protected $dontReport = [
//
];
/**
* A list of the inputs that are never flashed for validation exceptions.
*
* #var array
*/
protected $dontFlash = [
'password',
'password_confirmation',
];
/**
* Report or log an exception.
*
* #param \Throwable $exception
* #return void
*
* #throws \Exception
*/
public function report(Throwable $exception)
{
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Throwable $exception
* #return \Symfony\Component\HttpFoundation\Response
*
* #throws \Throwable
*/
public function render($request, Throwable $exception)
{
return parent::render($request, $exception);
}
}
For me it was related to Kernel.php
I was adding new schedule task into the Kernel. I also updated some controllers, views, and installed twilio extension.
The error did not provide more information than
Script #php artisan package:discover handling the post-autoload-dump event returned with error code 255
#Suresh Pangeni refences the Kernel.php doc so I checked by doc that is in PROJECTFOLDER\app\Console\Kernel.php
protected $commands = [
Commands\Inspire::class,
Commands\Test::class
\App\Console\Commands\Message::class,
];
Missing Comma between Commands\Test::class and the next line didn't let me proceed. It provided no further warning or information when I ran composer dump-autoload.
Hope this can help someone else that has a similar issue!
I had the same error today, the causes are as follows:
cause 1: the env file contains space in one of the configuration.
cause 2: incorrect configuration of the Handler file belonging to the App\Exceptions namespace;
cause 3: incorrect configuration of a file inheriting ExceptionHandler
I was using Laravel 9.x and got the same error after trying to install this package maatwebsite/excel!
thanks to #samuel-terra and #dqureshiumar there is the solution worked for me:
clear bootstrap/cache:
cd bootstrap/cache/
rm -rf *.php
then run composer update:
composer update
My problem was __construct method.
composer.json
"php": "^8.1",
"laravel/framework": "^9.19",
Handler.php
The problem originates from this code:
this->container->make(FlasherInterface::class);
My solution, I removed the construction directly and the problem is solved.
public function __construct(Container $container)
{
parent::__construct($container);
$this->flasher = $this->container->make(FlasherInterface::class);
//$this->request = $this->container->get(Request::class);
}
Getting this error when my composer version 2.x then i rollback this
composer self-update --1
Now its perfectly working

PhpStorm - Some warnings on Laravel facades

I make right usage of Laravel's facades and PhpStorm gives me warnings, why is that?
And on image I pointed "x" for some...types of data? In functions I use, why do I have these? How to remove them?
Using facades with Laravel
Luke Waite is right:
You're not using facades. You've imported the classes, and on the
first, Categories, the IDE is telling you that the get method is not a
static method.
Just import the facade instead (if it exist).
See the documentation on Facades to learn more on how to use the available facades and how to define your own.
A facade class should look like this:
use Illuminate\Support\Facades\Facade;
class Cache extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'cache';
}
}
Where the 'cache' string is the name of a service container binding and defined in a service provider, something like this:
use App\Cache\MyCache;
use Illuminate\Support\ServiceProvider;
class CacheServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
$this->app->singleton('cache', function ($app) {
return new MyCache();
});
}
}
Fixing the warnings with Facades
That being said, I was tired of the warnings and the missing auto-completion and highlighting with facades so I also searched to find a way to fix these.
I came upon laravel-ide-helper which adds Laravel CLI commands that generates php files that only serves to be parsed by your IDE.
Install
Require this package with composer using the following command:
composer require barryvdh/laravel-ide-helper
After updating composer, add the service provider to the providers
array in config/app.php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, To
install this package on only development systems, add the --dev flag
to your composer command:
composer require --dev barryvdh/laravel-ide-helper
In Laravel, instead of adding the service provider in the
config/app.php file, you can add the following code to your
app/Providers/AppServiceProvider.php file, within the register()
method:
public function register()
{
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
// ...
}
This will allow your application to load the Laravel IDE Helper on
non-production enviroments.
Automatic phpDoc generation for Laravel Facades
You can now re-generate the docs yourself (for future updates)
php artisan ide-helper:generate
Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating (and php artisan
optimize after).
You can configure your composer.json to do this after each commit:
"scripts":{
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan ide-helper:generate",
"php artisan ide-helper:meta",
"php artisan optimize"
]
},
The .phpstorm.meta.php and _ide_helper.php files will be generated and should be added to your .gitignore as you don't want to commit these.

Adding Sentry 2 config in Workbench Package

I am using laravel 4.1 and working on my own package in workbench. I added extra repo (sentry 2) in my package composer.json. Sentry is working properly but I can't override config by loading config files from workbench/package/name/src/config/packages/cartalyst/sentry/config.php
My service Provider looks like that:
public function boot()
{
// https://coderwall.com/p/svocrg
$this->package('package/name');
$config_path = __DIR__ . "/../../config/packages/cartalyst/sentry";
$this->app['config']->package('cartalyst/sentry', $config_path, 'cartalyst/sentry');
$this->app->register('Cartalyst\Sentry\SentryServiceProvider');
include __DIR__.'/../../routes.php';
}
public function register()
{
$this->app->booting(function()
{
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Sentry', 'Cartalyst\Sentry\Facades\Laravel\Sentry');
});
}
When I override something in config.php (workbench/package/name/src/config/packages/cartalyst/sentry/config.php) I still get things from vendor/cartalyst/sentry/src/config/config.php. How to properly load config in workbench package
I think you can't because as explained at official cartalyst sentry website "sentry is third party"
but you still can do some trick in your composer file in workbench.
at your composer.json in workbench :
"scripts": {
"post-install-cmd": [
"php artisan clear-compiled",
"php artisan optimize",
"php artisan app:sentry" /* add your own command which organize to create your own sentry configuration (remember mkdir cartalyst/sentry/config.php store to app/config/packages) */
],
// more
},
this mean, when your package in installing, your own command (e.g : php artisan app:sentry) will be executed
hope this help you...
Or, alternatively (more simple)
in your composer scripts key add :
"php artisan config:publish --package=cartalyst/sentry"
and then, at boot method in your PackageServiceProvider,
set your own configuration.
for example :
public function boot()
{
// for change user sentry model
\Config::set('sentry::config.user.model', 'Vendor\Package\YourUserModel');
}
I think this is more simplest way. :)
Example below show how i add config override of Basset in my package(workbench). You have to put this code in your register method in you service provider.
// Get config loader
$loader = $this->app['config']->getLoader();
// Add package namespace with path set base on your requirement
$loader->addNamespace('basset',__DIR__.'/../config/basset');
// Load package override config file
$configs = $loader->load($this->app['config']->getEnvironment(),'config','basset');
// Override value
$this->app['config']->set('basset::config',$configs);

Categories