I made a new command with:
php artisan make:console CrawlData
Then I changed two variables:
protected $signature = 'make:crawl';
protected $description = 'My crawling command';
The problem is that when I run:
php artisan make:crawl
It outputs:
[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "make:crawl" is not defined.
You also need to register the command in the App\Console\Kernel class for it to be recognized:
protected $commands = [
...
\App\Console\Commands\CrawlData::class,
];
You can read more about that in the Registering Commands documentation.
Starting with Laravel 5.5 commands in app/Console/Commands are automatically registered.
Related
I want to achieve task scheduling in my laravel 5.8 project. For that, I have created a custom artisan command artisan send: credentials which send emails to specific users based on their status.
sendUserCredentials.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Mail\credentialsEmail;
use App\Models\userModel;
use Mail;
class sendUserCredentials extends Command
{
protected $signature = 'send:credentials';
protected $description = 'Credentials send Successfully!';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$users = userModel::select(["email","username","role","id"])->where("credentials","NO")->get();
foreach ($users as $key => $user) {
Mail::to($user->email)->send(new credentialsEmail($user));
userModel::where("id",$user->id)->update(["credentials"=>"SEND"]);
}
}
}
I added this command in kernel.php so that I can run this command using the laravel task scheduler.
kernel.php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
Commands\sendUserCredentials::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('send:credentials')
->everyMinute();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
so on my local server, everything works like a charm when I run this command php artisan schedule:run
but on the shared server when I run scheduler using the cron command *****/path/to/project/artisan schedule:run >> /dev/null 2>&1 it gives me an error like this
local.ERROR: The Process class relies on proc_open, which is not available on your PHP installation. {"exception":"[object] (Symfony\\Component\\Process\\Exception\\LogicException(code: 0): The Process class relies on proc_open, which is not available on your PHP installation. at /path/to/vendor/vendor/symfony/process/Process.php:143)
BUT when I run the artisan command directly *****/path/to/project/artisan send:credentials >> /dev/null 2>&1 using the cron job then there is no error and emails send successfully!
I am using laravel 5.8 and deployed my website on namecheap shared hosting. Following command help me to execute cron job properly:
*/5 * * * * /usr/local/bin/php /home/YOUR_USER/public_html/artisan schedule:run >> /home/YOUR_USER/public_html/cronjobs.txt
As namecheap allow minimum of 5 min interval, so above command will execute after 5 min and output will be displayed in a text file.
The Error
The Process class relies on proc_open, which is not available on your PHP installation.
is because of Flare error reporting service enabled in debug mode. To solve this please follow the steps shared below.
Add the File /config/flare.php and add the below content
'reporting' => [
'anonymize_ips' => true,
'collect_git_information' => false,
'report_queries' => true,
'maximum_number_of_collected_queries' => 200,
'report_query_bindings' => true,
'report_view_data' => true,
],
And Clear the Bootstrap cache with below command
php artisan cache:clear && php artisan config:clear
Most probably the issue will be solved. Otherwise check once this link
I make
php artisan make:command BackupDatabaseCommand --command="command:backupdb"
I also registered firmly
app\Console\kernel.php
protected $commands = [
\App\Console\Commands\BackupDatabaseCommand::class,
];
But even if you try to execute the command i get here
The system cannot find the path specified.
I want to know how to solve it
Your path is wrong Since you are already in App\Console directory there is no need to specify App\Console it should be this:
protected $commands = [
Commands\BackupDatabaseCommand::class,
];
here is the image from my working project
Thanks
To Create command
php artisan make:command BackupDatabaseCommand --command=command:backupdb
You can register command as:
protected $commands = [
'App\Console\Commands\BackupDatabaseCommand'
];
and you can run command using:
php artisan command:backupdb
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 ;)
I have a cloned laravel application but when I try to generate a APP_KEY via php artisan key:generate it gives me an error:
In EncryptionServiceProvider.php line 42:
No application encryption key has been specified.
Which is obvious because that is exactly what I'm trying to create. Does anybody know how to debug this command?
update: Kind of fixed it with this post laravel 4: key not being generated with artisan
If I fill APP_KEY in my .env file php artisan key:generate works. But a newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
For some reason php artisan key:generate thinks it needs a app_key when it doesn't. It won't do any other commands either, they all error "No application encryption key has been specified."
php artisan key:generate needs an existing key to work. Fill the APP_KEY with 32 characters and rerun the command to make it work.
Edit: A newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
Edit a year later:
The real problems lays in 2 added provider services. The boot() functions are badly written which causes the problem. Still not exactly sure why it doesn't work but I'll try and figure it out for somebody who may have the same problem later.
The two files in question
<?php
namespace App\Providers;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class ResponseServiceProvider extends ServiceProvider
{
public function boot(ResponseFactory $factory){
parent::boot();
$factory->macro('api', function ($data=null, $code=null, $message=null) use ($factory) {
$customFormat = [
'status' => 'ok',
'code' => $code ? $code : 200,
'message' => $message ? $message : null,
'data' => $data
];
if ($data instanceof LengthAwarePaginator){
$paginationData = $data->toArray();
$pagination = isset($paginationData['current_page']) ? [
"total" => $paginationData['total'],
"per_page" => (int) $paginationData['per_page'],
"current_page" => $paginationData['current_page'],
"last_page" => $paginationData['last_page'],
"next_page_url" => $paginationData['next_page_url'],
"prev_page_url" => $paginationData['prev_page_url'],
"from" => $paginationData['from'],
"to" => $paginationData['to']
] : null;
if ($pagination){
$customFormat['pagination'] = $pagination;
$customFormat['data'] = $paginationData['data'];
}
}
return $factory->make($customFormat);
});
}
public function register(){
//
}
}
<?php
namespace App\Providers;
use App\Http\Controllers\Auth\SocialTokenGrant;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Bridge\UserRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\PassportServiceProvider;
use League\OAuth2\Server\AuthorizationServer;
/**
* Class CustomQueueServiceProvider
*
* #package App\Providers
*/
class SocialGrantProvider extends PassportServiceProvider{
/**
// * Bootstrap any application services.
// *
// * #return void
// */
public function boot(){
parent::boot();
app(AuthorizationServer::class)->enableGrantType($this->makeSocialRequestGrant(), Passport::tokensExpireIn());
}
/**
* Register the service provider.
*
* #return void
*/
public function register(){
}
/**
* Create and configure a SocialTokenGrant based on Password grant instance.
*
* #return SocialTokenGrant
*/
protected function makeSocialRequestGrant(){
$grant = new SocialTokenGrant(
$this->app->make(UserRepository::class),
$this->app->make(RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}
}
php artisan key:generate is a command that create a APP_KEY value in your .env file.
When you run composer create-project laravel/laravel command it will generate a APP_Key in .env file, but when you checkout a new branch by git or clone a new project, the .env file will not include, so you have to run artisan key:generate to create a new APP_KEY.
You changed your question. In this case, you can try it.
php artisan key:generate
php artisan config:cache
If you don't have a vendor folder then,
1) Install composer dependencies
composer install
2) An application key APP_KEY need to be generated with the command
php artisan key:generate
3) Open Project in a Code Editor, rename .env.example to .env and modify DB name, username, password to your environment.
4) php artisan config:cache to effect the changes.
check your .env file. Is it exists?
I use Lumen 1.0 for an API project.
I have already enable Eloquent by uncomment the following line in bootstrap/app.php file :
$app->withEloquent();
But when I want to create my first model with migration it fails :
php artisan make:model Book --migration
Error message :
[InvalidArgumentException]
Command "make:model" is not defined.
Did you mean one of these?
make:seeder
make:migration
Laravel doc about Eloquent (http://laravel.com/docs/5.1/eloquent#defining-models).
Lumen doc (http://lumen.laravel.com/docs/installation) doesn't include Eloquent doc because, it's not enable by default.
Do you have any ideas to avoid this error ?
Add details
php artisan --version
Displays :
Laravel Framework version Lumen (5.1.6) (Laravel Components 5.1.*)
You're seeing this error because Lumen doesn't come with make:model.
To see a list of all the artisan commands you have at your disposal just run php artisan.
That being said I did just find this package which I've added to a lumen installation and it seems to work fine https://github.com/webNeat/lumen-generators#installation
Hope this helps!
If you check all the available commands using php artisan list you will see that you don't have all the default ones offered by laravel. But you can get the most importants using the lumen-generator package (not to be confused with lumen-generators). It has the advantage of offering more commands than the other one mentioned.
To use it just install it using composer:
composer require flipbox/lumen-generator
Then enable it in your bootstrap/app.php file:
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class);
You will now be able to use all these new commands using artisan:
key:generate Set the application key
make:command Create a new Artisan command
make:controller Create a new controller class
make:event Create a new event class
make:job Create a new job class
make:listener Create a new event listener class
make:mail Create a new email class
make:middleware Create a new middleware class
make:migration Create a new migration file
make:model Create a new Eloquent model class
make:policy Create a new policy class
make:provider Create a new service provider class
make:seeder Create a new seeder class
make:test Create a new test class
Just have a look at the official documentation: https://github.com/flipboxstudio/lumen-generator
Go to the project directory and add the generators package to your composer.json using the following command:
composer require wn/lumen-generators
Add following code segment to app/Providers/AppServiceProvider.php:
public function register()
{
if ($this->app->environment() == 'local') {
$this->app->register('Wn\Generators\CommandsServiceProvider');
}
}
Make sure that you have un-commented the following line in bootstrap/app.php to allow service providers on your project:
$app->register(App\Providers\AppServiceProvider::class);
Run php artisan list on the project directory (document root). Now you will see new items there.
just create your model file manually in the app directory
example
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model {
protected $table = ‘articles’;
protected $fillable = [
‘title’,
‘description’,
‘body’
];
}
$app->register(Flipbox\LumenGenerator\LumenGeneratorServiceProvider::class); add this line into "bootstrap\app.php" and save this file then make the command.It will work.
there are some packages that can help you to have all of artisan command that you has on Laravel .
install below package to have more artisan command.
https://github.com/flipboxstudio/lumen-generator