How to call a handle method into an routes.php file? - php

I want to print a log message when i run php artisan make:greetings command in my command line it should return a message in my log file , for that how to call a handle method inside the routes.php file, for that i am writing some code but i am getting a following error please help me to fix this issue
Error
TypeError
Argument 2 passed to Illuminate\Foundation\Console\Kernel::command() must be an instance of Closure, array given,
called in C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 261
at C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Foundation\Console\Kernel.php:191
187▕ * #param string $signature
188▕ * #param \Closure $callback
189▕ * #return \Illuminate\Foundation\Console\ClosureCommand
190▕ */
➜ 191▕ public function command($signature, Closure $callback)
192▕ {
193▕ $command = new ClosureCommand($signature, $callback);
194▕
195▕ Artisan::starting(function ($artisan) use ($command) {
1 C:\apiato-project\apiato\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php:261
Illuminate\Foundation\Console\Kernel::command("make:greetings", ["App\Console\Commands\Hello"])
2 C:\apiato-project\apiato\app\Ship\Commands\Routes.php:24
Illuminate\Support\Facades\Facade::__callStatic("command")
routes.php
Artisan::command('make:greetings',[Hello::class,'handle'=>true]);
Hello.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Log;
class Hello extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'make:greetings';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return int
*/
public function handle()
{
return Log::info("welcome message");
}
}

The second argument have to be a closure and you are passing an array, This closure is used to pass data to your handle method and as you dont have any arguments in your handle method use call method istead of command, Try this:
Artisan::call('make:greetings');
and also don't forget to register your command in App\Console\Kernel class:
protected $commands = [
'App\Console\Commands\Hello',
];

Related

Generate multiple files with laravel command

could you help me with a problem that I have? I have created a command with php artisan make:command to generate repository type classes from existing models. The problem is that I need that instead of generating a single file from a stub, I need to generate 2 or more files. I can't find documentation regarding the subject. Currently what I have achieved is that I only generate a single file from a template.
<?php
namespace App\Console\Commands;
use Illuminate\Console\GeneratorCommand;
use Symfony\Component\Console\Input\InputArgument;
class MakeRepository extends GeneratorCommand
{
/**
* The console command name.
*
* #var string
*/
protected $name = 'make:repository';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Create a new repository';
/**
* The type of class being generated.
*
* #var string
*/
protected $type = 'Repository';
/**
* #inheritDoc
*/
protected function getStub()
{
return __DIR__ . '/stubs/MakeRepository/ModelRepositoryInterface.stub';
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the model to which the repository will be generated'],
];
}
/**
* Get the default namespace for the class.
*
* #param string $rootNamespace
* #return string
*/
protected function getDefaultNamespace($rootNamespace)
{
return $rootNamespace.'\Repositories';
}
}
EDIT #1
I have 2 stub files inside the directory:
app/Console/Commands/stubs/MakeRepository
ModelRepository.stub
ModelRepositoryInterface.stub
I want that when you execute the command...ex: php artisan make:repository Blog, these 2 files are created in the following directory:
/app/Repositories/Blog/BlogRepository.php
/app/Repositories/Blog/BlogRepositoryInterface.php
You can write a new command to create repository interface, and then call it in MakeRepository.
I think this method is in line with SRP.
// In MakeRepository.php
// Override handle method
public function handle()
{
if (parent::handle() === false && ! $this->option('force')) {
return false;
}
if ($this->option('interface')) {
$this->call('make:repository-interface', ['name' => $this->getNameInput() . 'Interface']);
}
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the model to which the repository will be generated'],
['interface', 'i', InputOption::VALUE_NONE, 'Create a new interface for the repository'],
];
}
You can also refer to the code of make model of official.
https://github.com/laravel/framework/blob/6.x/src/Illuminate/Foundation/Console/ModelMakeCommand.php
you can use glob to get your stubs in array then loop over them to create the multiple files
foreach(glob(stubs_path('stubs/Repository/*.stub') as $stub){
copy(stubs_path('stubs/Repository/'.$stub), $repositoryLocation . 'Repository.php');
}

Laravel: Interface 'Illuminate\Contracts\Queue\QueueableCollection' not found

I am creating a console (Artisan) command to run a custom-made package. The import of the package and all of its functions is working just fine, but I can't seem to query any eloquent models without having the following error pop up:
[Symfony\Component\Debug\Exception\FatalErrorException]
Interface 'Illuminate\Contracts\Queue\QueueableCollection' not found
Here is my code...
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Property;
use Sync;
class SyncTool extends Command {
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'sync:all';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$credentials = [
...
];
$sync = new Sync( $credentials );
$properties = Property::all(); // this throws the error
}
}
Step 1 : Remove full vendor folder
Step 2: delete /bootstrap/cache/services.php, /bootstrap/cache/compiled.php
Step 3 : Run from your terminal composer install
try this

ARGUMENTS and OPTIONS with Laravel Illuminate Console Command

It's pretty clear how to create a simple command for the CLI in Laravel and this goes also for creating arguments, but I can't seem to find a simple documentation on how to create options for the CLI.
I want to make it so that the user can add options after the argument.
So for example:
php artisan cmd argument -a
php artisan cmd argument -a -c -x
How do I implement such a structure in the class below?
Updated code
There are indeed a few possible solutions. It was actually quit easy.
class cmd extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'cmd {argument}
{--s : description}
{--x : description}';
/**
* The console command description.
*
* #var string
*/
protected $description = 'description';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$var = $this->argument('argument');
$options = $this->options();
new Main($var,$options);
}
}
There are a lot of posible solutions for this, but I prefer to add optional arguments and if they exist do determinate actions with the ? that means argument can exist or not, plus * this means can be more tan one, like this:
class cmd extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'cmd {argument} {-extra*?}';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$var = $this->argument('argument');
if($this->argument('-extra')) {
//do things if -extra argument exists, it will be an array with the extra arguments value...
}
new Main($var);
}
}
There a whole doc section dedicated to creating commands from scratch and it's well documented. Look through it.
https://laravel.com/docs/5.4/artisan
If you need to learn from examples then have a look here into all the laravel's built in console commands.
vendor/laravel/framework/src/Illuminate/Foundation/Console

Set Up CronJob In CPanel Laravel

i set up a cronjob in cpanel, i'm using laravel 4.2. i also set to send the cronjob to my email and below yellow part is the error i received in email.
[InvalidArgumentException]
There are no commands defined in the "user" namespace.
//laravel command.php
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class CronDelFilesCommand extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'user:active';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function fire()
{
echo "aaa";
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return array(
);
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return array(
array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
);
}
}
//command in cpanel
* * * * * /usr/bin/php /home/project/public_html/artisan user:active > /home/project/public_html/log.txt
what's wrong? what's the error mean?
UPDATED
thanks to #KristianHareland i use wget. :)
I think you forget to add this command to artisan app/start/artisan.php.
You shoud wright:
Artisan::add(new CronDelFilesCommand());
And don't forget about composer dump-autoload
More info you can find here.

laravel 4.2 artisan command:name with arguments

I have created an artisan command called sendUnreadNotifications this triggers the system to send users emails if they have unread notifications. Eventually this will be run via a cron job, and a user can either have hourly updates or daily updates.
For this reason I am wanting to send an argument with my command, something like this,
php artisan command:name sendUnreadNotifications H --env=local
However running this, I get the following error,
[RuntimeException]
Too many arguments.
My code, looks like this,
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class sendUnreadNotifications extends Command {
/**
* The console command name.
*
* #var string
*/
protected $name = 'command:name';
/**
* The console command description.
*
* #var string
*/
protected $description = 'Command description.';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function fire()
{
$request = Request::create('api/notifications/send/unread', 'GET', array($this->getArguments()));
Route::dispatch($request)->getContent();
}
/**
* Get the console command arguments.
*
* #return array
*/
protected function getArguments()
{
return array(
array('frequency', InputArgument::OPTIONAL, 'How often should the email be sent', 'H'),
);
}
/**
* Get the console command options.
*
* #return array
*/
protected function getOptions()
{
return array(
array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
);
}
}
I cannot see why I would be getting the too many arguments exception?
You do only have one argument set, for frequency
protected function getArguments()
{
return array(
array('frequency', InputArgument::OPTIONAL, 'How often should the email be sent', 'H'),
);
}
so the
php artisan command:name sendUnreadNotifications H --env=local
here the H is the argument that is too much. You should change your command's name to what you want to do, the command names need to be unique btw...
Change this:
protected $name = 'command:name';
to
protected $name = 'send:unreadNotifications';
and run your job with
php artisan send:UnreadNotifications H
and it will work.

Categories