laravel artisan console

 php artisan list

Usage:

  command [options] [arguments]


Options:

  -h, --help            Display help for the given command. When no command is given display help for the list command

  -q, --quiet           Do not output any message

  -V, --version         Display this application version

      --ansi|--no-ansi  Force (or disable --no-ansi) ANSI output

  -n, --no-interaction  Do not ask any interactive question

      --env[=ENV]       The environment the command should run under

  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug


Available commands:

  clear-compiled                Remove the compiled class file

  completion                    Dump the shell completion script

  db                            Start a new database CLI session

  down                          Put the application into maintenance / demo mode

  env                           Display the current framework environment

  help                          Display help for a command

  inspire                       Display an inspiring quote

  list                          List commands

  migrate                       Run the database migrations

  optimize                      Cache the framework bootstrap files

  serve                         Serve the application on the PHP development server

  test                          Run the application tests

  tinker                        Interact with your application

  ui                            Swap the front-end scaffolding for the application

  up                            Bring the application out of maintenance mode

 auth

  auth:clear-resets             Flush expired password reset tokens

 cache

  cache:clear                   Flush the application cache

  cache:forget                  Remove an item from the cache

  cache:table                   Create a migration for the cache database table

 config

  config:cache                  Create a cache file for faster configuration loading

  config:clear                  Remove the configuration cache file

 db

  db:seed                       Seed the database with records

  db:wipe                       Drop all tables, views, and types

 event

  event:cache                   Discover and cache the application's events and listeners

  event:clear                   Clear all cached events and listeners

  event:generate                Generate the missing events and listeners based on registration

  event:list                    List the application's events and listeners

 key

  key:generate                  Set the application key

 make

  make:cast                     Create a new custom Eloquent cast class

  make:channel                  Create a new channel class

  make:command                  Create a new Artisan command

  make:component                Create a new view component class

  make:controller               Create a new controller class

  make:event                    Create a new event class

  make:exception                Create a new custom exception class

  make:factory                  Create a new model factory

  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:notification             Create a new notification class

  make:observer                 Create a new observer class

  make:policy                   Create a new policy class

  make:provider                 Create a new service provider class

  make:request                  Create a new form request class

  make:resource                 Create a new resource

  make:rule                     Create a new validation rule

  make:seeder                   Create a new seeder class

  make:test                     Create a new test class

 migrate

  migrate:fresh                 Drop all tables and re-run all migrations

  migrate:install               Create the migration repository

  migrate:refresh               Reset and re-run all migrations

  migrate:reset                 Rollback all database migrations

  migrate:rollback              Rollback the last database migration

  migrate:status                Show the status of each migration

 model

  model:prune                   Prune models that are no longer needed

 notifications

  notifications:table           Create a migration for the notifications table

 optimize

  optimize:clear                Remove the cached bootstrap files

 package

  package:discover              Rebuild the cached package manifest

 permission

  permission:cache-reset        Reset the permission cache

  permission:create-permission  Create a permission

  permission:create-role        Create a role

  permission:setup-teams        Setup the teams feature by generating the associated migration.

  permission:show               Show a table of roles and permissions per guard

 queue

  queue:batches-table           Create a migration for the batches database table

  queue:clear                   Delete all of the jobs from the specified queue

  queue:failed                  List all of the failed queue jobs

  queue:failed-table            Create a migration for the failed queue jobs database table

  queue:flush                   Flush all of the failed queue jobs

  queue:forget                  Delete a failed queue job

  queue:listen                  Listen to a given queue

  queue:monitor                 Monitor the size of the specified queues

  queue:prune-batches           Prune stale entries from the batches database

  queue:prune-failed            Prune stale entries from the failed jobs table

  queue:restart                 Restart queue worker daemons after their current job

  queue:retry                   Retry a failed queue job

  queue:retry-batch             Retry the failed jobs for a batch

  queue:table                   Create a migration for the queue jobs database table

  queue:work                    Start processing jobs on the queue as a daemon

 route

  route:cache                   Create a route cache file for faster route registration

  route:clear                   Remove the route cache file

  route:list                    List all registered routes

 sail

  sail:install                  Install Laravel Sail's default Docker Compose file

  sail:publish                  Publish the Laravel Sail Docker files

 sanctum

  sanctum:prune-expired         Prune tokens expired for more than specified number of hours.

 schedule

  schedule:clear-cache          Delete the cached mutex files created by scheduler

  schedule:list                 List the scheduled commands

  schedule:run                  Run the scheduled commands

  schedule:test                 Run a scheduled command

  schedule:work                 Start the schedule worker

 schema

  schema:dump                   Dump the given database schema

 session

  session:table                 Create a migration for the session database table

 storage

  storage:link                  Create the symbolic links configured for the application

 stub

  stub:publish                  Publish all stubs that are available for customization

 ui

  ui:auth                       Scaffold basic login and registration views and routes

  ui:controllers                Scaffold the authentication controllers

 vendor

  vendor:publish                Publish any publishable assets from vendor packages

 view

  view:cache                    Compile all of the application's Blade templates

  view:clear                    Clear all compiled view files


artisan existas at root \


php artisan help migration to know this migrationfulld etails


create custom command

php artisan make:command sendemails

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\Order;

class MakeOrdersDelivery extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'orders:delivery';

/**
* The console command description.
*
* @var string
*/
protected $description = 'Delivery the orders which is in crossed the 40 minutes after placed order';

/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}

/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$t=time();
$duration = 7200;
$now_date =date("Y-m-d H:i:s",$t);
$schedule_date = date("Y-m-d H:i:s",$t-60*$duration);
$orders= Order::where('deleted_at', null)
->whereBetween('created_at', [ $schedule_date, $now_date ])
->where('status','!=', 'delivered')
->pluck('id');
$count = $orders->count();
if($orders->count()){
foreach ($orders as $order_id) {
$order= Order::where('deleted_at', null)
-> where('id',$order_id)->first();
$order->update(['status' => 'delivered']);
}
echo "Delivered the orders which is in crossed the 40 minutes after placed order";
} else {
echo "no orders now";
}
}
}



artisan console closure commands


closure command alretnative to console commands




app/console/kernel php

schedule

commands

<?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('orders:delivery')->everyThirtyMinutes();
}

/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');

require base_path('routes/console.php');
}
}


go to routes/console.php

<?php

use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;

/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/

Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');


php artisan inspire

for eveyr time it show some quites

closure -> {user}

fucntion(argumentsy)


cuystom commands in console.php

Artisan::command('order:delivery', function () {
$this->comment("Delivered the orders which is in crossed the 40 minutes after placed order");
})->purpose('notifyu orders');


php artisan order:delivery


php arisan console input expectations

create-task:reports {date?}

https://laravel.com/docs/10.x/artisan#defining-input-expectations


create-task:reports {date=22-02-2022}


Artisan::command('order:delivery {date=22-02-2022}', function ($date) {


Artisan::command('order:delivery {user=vamsi}', function ($user) {

$this->comment($user);
})->purpose('notifyu orders');


Artisan::command('order:delivery {user=vamsi}', function ($user) {

$this->comment($user);
$arg= $this->argument('user');
})->purpose('notifyu orders');


Artisan::command('order:delivery {user=vamsi} {--opt}', function ($user,$opt) {

$this->comment($user);
$this->comment($opt);
$arg= $this->argument('user');
})->purpose('notifyu orders');


https://laravel.com/docs/10.x/artisan#defining-input-expectations

multiple arguments


/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user}';

You may also make arguments optional or define default values for arguments:

// Optional argument...
'mail:send {user?}'
 
// Optional argument with default value...
'mail:send {user=foo}'

Options

Options, like arguments, are another form of user input. Options are prefixed by two hyphens (--) when they are provided via the command line. There are two types of options: those that receive a value and those that don't. Options that don't receive a value serve as a boolean "switch". Let's take a look at an example of this type of option:

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue}';

In this example, the --queue switch may be specified when calling the Artisan command. If the --queue switch is passed, the value of the option will be true. Otherwise, the value will be false:

php artisan mail:send 1 --queue

Options With Values

Next, let's take a look at an option that expects a value. If the user must specify a value for an option, you should suffix the option name with a = sign:

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send {user} {--queue=}';

In this example, the user may pass a value for the option like so. If the option is not specified when invoking the command, its value will be null:

php artisan mail:send 1 --queue=default

You may assign default values to options by specifying the default value after the option name. If no option value is passed by the user, the default value will be used:

'mail:send {user} {--queue=default}'

Option Shortcuts

To assign a shortcut when defining an option, you may specify it before the option name and use the | character as a delimiter to separate the shortcut from the full option name:

'mail:send {user} {--Q|queue}'

When invoking the command on your terminal, option shortcuts should be prefixed with a single hyphen and no = character should be included when specifying a value for the option:

php artisan mail:send 1 -Qdefault

Input Arrays

If you would like to define arguments or options to expect multiple input values, you may use the * character. First, let's take a look at an example that specifies such an argument:

'mail:send {user*}'

When calling this method, the user arguments may be passed in order to the command line. For example, the following command will set the value of user to an array with 1 and 2 as its values:

php artisan mail:send 1 2

This * character can be combined with an optional argument definition to allow zero or more instances of an argument:

'mail:send {user?*}'

Option Arrays

When defining an option that expects multiple input values, each option value passed to the command should be prefixed with the option name:

'mail:send {--id=*}'

Such a command may be invoked by passing multiple --id arguments:

php artisan mail:send --id=1 --id=2

Input Descriptions

You may assign descriptions to input arguments and options by separating the argument name from the description using a colon. If you need a little extra room to define your command, feel free to spread the definition across multiple lines:

/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mail:send
{user : The ID of the user}
{--queue : Whether the job should be queued}';

Command I/O

Retrieving Input

While your command is executing, you will likely need to access the values for the arguments and options accepted by your command. To do so, you may use the argument and option methods. If an argument or option does not exist, null will be returned:

/**
* Execute the console command.
*/
public function handle(): void
{
$userId = $this->argument('user');
}

If you need to retrieve all of the arguments as an array, call the arguments method:

$arguments = $this->arguments();



laravel artisan console command i-0



$this->ask('what is uour name?');


Artisan::command('name:know ', function () {
$name = $this->ask('waht is your name?');
$this -> comment('yourname is '. $name);
})->purpose('notifyu orders');






https://laravel.com/docs/8.x/artisan#prompting-for-input

Prompting For Input

In addition to displaying output, you may also ask the user to provide input during the execution of your command. The ask method will prompt the user with the given question, accept their input, and then return the user's input back to your command:

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$name = $this->ask('What is your name?');
}

The secret method is similar to ask, but the user's input will not be visible to them as they type in the console. This method is useful when asking for sensitive information such as passwords:

$password = $this->secret('What is the password?');

Asking For Confirmation

If you need to ask the user for a simple "yes or no" confirmation, you may use the confirm method. By default, this method will return false. However, if the user enters y or yes in response to the prompt, the method will return true.

if ($this->confirm('Do you wish to continue?')) {
//
}

If necessary, you may specify that the confirmation prompt should return true by default by passing true as the second argument to the confirm method:

if ($this->confirm('Do you wish to continue?', true)) {
//
}

Auto-Completion

The anticipate method can be used to provide auto-completion for possible choices. The user can still provide any answer, regardless of the auto-completion hints:

$name = $this->anticipate('What is your name?', ['Taylor', 'Dayle']);

Alternatively, you may pass a closure as the second argument to the anticipate method. The closure will be called each time the user types an input character. The closure should accept a string parameter containing the user's input so far, and return an array of options for auto-completion:

$name = $this->anticipate('What is your address?', function ($input) {
// Return auto-completion options...
});

Multiple Choice Questions

If you need to give the user a predefined set of choices when asking a question, you may use the choice method. You may set the array index of the default value to be returned if no option is chosen by passing the index as the third argument to the method:

$name = $this->choice(
'What is your name?',
['Taylor', 'Dayle'],
$defaultIndex
);

In addition, the choice method accepts optional fourth and fifth arguments for determining the maximum number of attempts to select a valid response and whether multiple selections are permitted:

$name = $this->choice(
'What is your name?',
['Taylor', 'Dayle'],
$defaultIndex,
$maxAttempts = null,
$allowMultipleSelections = false
);

Writing Output

error,line,info,comment

To send output to the console, you may use the lineinfocommentquestionwarn, and error methods. Each of these methods will use appropriate ANSI colors for their purpose. For example, let's display some general information to the user. Typically, the info method will display in the console as green colored text:

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// ...
 
$this->info('The command was successful!');
}

To display an error message, use the error method. Error message text is typically displayed in red:

$this->error('Something went wrong!');

You may use the line method to display plain, uncolored text:

$this->line('Display this on the screen');

You may use the newLine method to display a blank line:

// Write a single blank line...
$this->newLine();
 
// Write three blank lines...
$this->newLine(3);

Tables

The table method makes it easy to correctly format multiple rows / columns of data. All you need to do is provide the column names and the data for the table and Laravel will automatically calculate the appropriate width and height of the table for you:

use App\Models\User;
 
$this->table(
['Name', 'Email'],
User::all(['name', 'email'])->toArray()
);



Progress Bars

Artisan::command('progreess:bar ', function () {
$this->output->progressStart(10);
for ($i=0;$i<100;$i++)
{
sleep(1);
$this->output->progressAdvance();
}
$this->output->progressFInish();
})->purpose('progress bar');




For long running tasks, it can be helpful to show a progress bar that informs users how complete the task is. Using the withProgressBar method, Laravel will display a progress bar and advance its progress for each iteration over a given iterable value:

use App\Models\User;
 
$users = $this->withProgressBar(User::all(), function ($user) {
$this->performTask($user);
});

Sometimes, you may need more manual control over how a progress bar is advanced. First, define the total number of steps the process will iterate through. Then, advance the progress bar after processing each item:

$users = App\Models\User::all();
 
$bar = $this->output->createProgressBar(count($users));
 
$bar->start();
 
foreach ($users as $user) {
$this->performTask($user);
 
$bar->advance();
}
 
$bar->finish();



artisan console programatically executing command

Programmatically Executing Commands

Sometimes you may wish to execute an Artisan command outside of the CLI. For example, you may wish to execute an Artisan command from a route or controller. You may use the call method on the Artisan facade to accomplish this. The call method accepts either the command's signature name or class name as its first argument, and an array of command parameters as the second argument. The exit code will be returned:

before below we have to write a commnd  in commands folder app/console/commands

use Illuminate\Support\Facades\Artisan;
 
Route::post('/user/{user}/mail', function ($user) {
$exitCode = Artisan::call('mail:send', [
'user' => $user, '--queue' => 'default'
]);
 
//
});

Alternatively, you may pass the entire Artisan command to the call method as a string:

Artisan::call('mail:send 1 --queue=default');

Passing Array Values

If your command defines an option that accepts an array, you may pass an array of values to that option:

use Illuminate\Support\Facades\Artisan;
 
Route::post('/mail', function () {
$exitCode = Artisan::call('mail:send', [
'--id' => [5, 13]
]);
});

Passing Boolean Values

If you need to specify the value of an option that does not accept string values, such as the --force flag on the migrate:refresh command, you should pass true or false as the value of the option:

$exitCode = Artisan::call('migrate:refresh', [
'--force' => true,
]);

Queueing Artisan Commands

Using the queue method on the Artisan facade, you may even queue Artisan commands so they are processed in the background by your queue workers. Before using this method, make sure you have configured your queue and are running a queue listener:

use Illuminate\Support\Facades\Artisan;
 
Route::post('/user/{user}/mail', function ($user) {
Artisan::queue('mail:send', [
'user' => $user, '--queue' => 'default'
]);
 
//
});

Using the onConnection and onQueue methods, you may specify the connection or queue the Artisan command should be dispatched to:

Artisan::queue('mail:send', [
'user' => 1, '--queue' => 'default'
])->onConnection('redis')->onQueue('commands');

Calling Commands From Other Commands

Sometimes you may wish to call other commands from an existing Artisan command. You may do so using the call method. This call method accepts the command name and an array of command arguments / options:

/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
$this->call('mail:send', [
'user' => 1, '--queue' => 'default'
]);
 
//
}

If you would like to call another console command and suppress all of its output, you may use the callSilently method. The callSilently method has the same signature as the call method:

$this->callSilently('mail:send', [
'user' => 1, '--queue' => 'default'
]);


laravel teask scheduler

https://laravel.com/docs/8.x/scheduling




MethodDescription
->cron('* * * * *');Run the task on a custom cron schedule
->everyMinute();Run the task every minute
->everyTwoMinutes();Run the task every two minutes
->everyThreeMinutes();Run the task every three minutes
->everyFourMinutes();Run the task every four minutes
->everyFiveMinutes();Run the task every five minutes
->everyTenMinutes();Run the task every ten minutes
->everyFifteenMinutes();Run the task every fifteen minutes
->everyThirtyMinutes();Run the task every thirty minutes
->hourly();Run the task every hour
->hourlyAt(17);Run the task every hour at 17 minutes past the hour
->everyTwoHours();Run the task every two hours
->everyThreeHours();Run the task every three hours
protected function schedule(Schedule $schedule)
{
$schedule->command('orders:delivery')->everyThirtyMinutes();
}

php artisan schedule:list

php artisan schedule:work for running locally


cron-> second or minute 

protected function schedule(Schedule $schedule)
{
$schedule ->command('inspire')->everyMinute();
$schedule->command('orders:delivery')->everyThirtyMinutes();
}











  1. What is Artisan in Laravel?

    Marked Answer : CLI

    Correct Answer : CLI

  2. Which command is used to list all artisan command?

    Marked Answer : command:list

    Correct Answer : list

  3. How to retrieve all the arguments as an array?

    Marked Answer : $this->arguments();

    Correct Answer : $this->arguments();

  4. Which method is used to prompt for password?

    Marked Answer : secret()

    Correct Answer : secret()

  5. Which façade is used to programmatically executing commands?

    Marked Answer : Queue























sd


No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...