Laravel 8 Custom Command Example Tutorial

Laravel 6 , Laravel , Laravel 7 , Laravel 8

Nicesnippets

839

22-09-2020


Laravel 8 Custom Command Example Tutorial

Hi Guys,

Today,I will learn you how to create custom command in laravel 8.We will show example of laravel 8 custom command. I make our own artisan command for like project setup, create new admin user etc in our laravel 8 application. If I create custom command then we can make project setup like create one admin user, run migration, run seeder and etc. In this post we give you example, how to create console commands in laravel 8 project.

In this example I will create custom command for create new admin user. This custom command will ask your name, email and password.

Custom command


php artisan users:create

This command through we will create new admins. So first fire bellow command and create console class file.

php artisan make:command UserCommand --command=users:create

Next this command you can find one file UserCommand class in console directory. so one that file and put bellow code.

app/Console/Commands/UserCommand.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

use App\Models\User;

use Hash;

class UserCommand extends Command

{

/**

* The name and signature of the console command.

*

* @var string

*/

protected $signature = 'users:create';

/**

* 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()

{

$input['name'] = $this->ask('Your name?');

$input['email'] = $this->ask('Your email?');

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

$input['password'] = Hash::make($input['password']);

User::create($input);

$this->info('User Create Successfully.');

}

}

After, Now I need to register this command class in Kernel.php file, so open file and add class this way:

<?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 = [

Commands\UserCommand::class,

];

/**

* Define the application's command schedule.

*

* @param \Illuminate\Console\Scheduling\Schedule $schedule

* @return void

*/

protected function schedule(Schedule $schedule)

{

}

}

Now we are ready to use or custom command, you fire bellow command and check you can find command in the list this way "users:create".

php artisan list

php artisan users:create

It Will help you...


Recommended Posts