Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Laravel Custom Commands

$
0
0

Overview

Uses :

Custom Commands is used when we need to check something or track something on particular time period, for example : we need to send mail to notification mail to user when his subscription period is near to expire or we need to send feedback form to new user after one month to know their experience, etc.

So in this case we will create custom command and we set cron job that execute our command.

Now the question is how to make custom command?

Laravel Initial SetUp

Let’s start with a new fresh project.
*For Understanding Purpose we make it simple by using only two tables “users and posts”

  • Create new project
    laravel new custom
  • Set up SQL connection in .env file
  • Make new migration table : posts
    php artisan make:migration create_post_table create=posts
  • Add few columns like title, description, user_id(foreign constraint)
  • Migrate database
    php artisan migrate
  • Make Eloquent Model For User(if not exists) and Posts

Set Up Relationship (*optional)

1) Define relationships and add accessor in Post Eloquent Mode. (*optional)

public function user()
{
    return $this->belongsTo('App\User');
}

public function getCreatedAtAttribute($value)
{
    return \Carbon\Carbon::parse($value)->diffForHumans();
}

Same as Post Eloquent, add relationship and accessor in User Eloquent Model

public function posts()
{
    return $this->hasMany('App\Post');
}

public function getNameAttribute($value)
{
    return title_case($value);
}

2) Add few records in a database. (manually from phpMyAdmin)
3) As of now, the Basic app is to understand the custom commands.

Simple Commands

Generate Command File

php artisan make:command {command_name}
php artisan make:command allUsers

Structure Of Command

  • After generating your command, you should fill in the signature and description properties of the class, which will be used when displaying your command on the list screen.
  • The handle method will be called when your command is executed.
  • You may place your command logic in this method.

Here one new command file is created : App\Console\Commands\allUsers.php

Now Modify our new command file:

protected $signature = 'command:name';

Signature Means : The command used after php artisan

So change signature variable to :

protected $signature = 'user:all';

Change the description :

protected $description = 'Get All Users.';

This message is displayed in the help section of our command.

Now, an actual part of the command is here:

We need to add our logic part at

public function handle()
{
    // Add Your Logic / Task 
}

In this example we need to select user details, so add :

$users = User::select('id','name','email','contact')
    ->orderBy('name')
    ->get()
    ->toArray();

$this->table(['id','name','email','contact'],$users);

NOTE :

  • If You Want to display details in tabular format, “toArray()” is required.
  • In the table() we need to pass the column name(s) and array for that columns.
  • Artisan CLI can manage the output as a table for GUI purpose (if needed).

Output :
Now, our command is ready to execute.
Go to terminal and execute the command

php artisan user:all

laravel-image1

Print Details On Command Line :

$this->info("message");	          // success message

$this->error("message")          // error message

Get Input In Through Command Line

As of now we know how to fire custom command, now understand how to get input from command line and process that input.

Let’s make new command which fetches particular user’s details.

php artisan make:command userDetails

Change signature of our command :

protected $signature = 'user:get { id : ID Of User}';

Note :

  • Here, {variable : description} is used to get input from user.
  • As per our signature command will look like
    php artisan user:get 1
  • Here we can also pass optional values by adding {id?} so “?” is used for optional values.
  • If you want to add some options then use {–option_name}, if you want to add shortcut then {– A | argument } and you can access that value by using switch case
  • If you have not fixed a length of output then you can use an array for it by adding *.
    Example :
    • COMMAND FILE : $signature = ‘user:get {– id =*}’;
    • TERMINAL : php artisan user:get –id=1 –id=2

Now add our logic part / task at

public function handle()
{
	// Add Your Logic / Task 
}

To use input of CLI :

$this->argument("argument_name");

In this example we need to select user details, post details, so add :

$bar = $this->output->createProgressBar(100);
$user_details = User::select('id','name','email','contact')
          ->where('id', $this->argument('id'))->get()->toArray();

if(sizeof($user_details) == 0) {
    $this->error("User Not Found!");
        $bar->advance();
    }
    else {
        $this->info("User Details");
        $this->table(['id','name','email','contact'],$user_details);
        $post_details = Post::select('title','description','created_at')
	          ->where('user_id',$this->argument('id'))->get()->toArray();
        $bar->advance(50);

        if(sizeof($post_details) == 0) {
            $this->error("No Post Found!");
        } else {
            $this->info("\n\nUser's Posts Details");
            $this->table(['Title','Description','Created By'],$post_details);
            $this->info("\nTotal Post(s) : ".sizeof($post_details));
            $bar->advance(50);
        }
    }
$bar->finish();
$this->info(''); // this is for new line

In above example we add ProgressBar, ProgressBar is used to get tracking information and nothing else.

  • First, we need to init ProgressBar with max.
  • After that just use advance() with an argument, the number of increment default is 1.
  • To complete the use of ProgressBar, use finish() to end that ProgressBar.
  • ProgressBar Is Completely Optional. It is only for GUI Purpose Only!

Output :
Now, our command is ready to execute.
Go to terminal and execute the command

php artisan user:get 1

laravel-image2

php artisan user:all

php artisan post:all

laravel-image3

Conclusion : –

That’s It! I hope you found out my article useful. For any suggestions, please hit comment below.

Thank You!


Viewing all articles
Browse latest Browse all 595

Trending Articles