1. Introduction
Artisan is the command line interface that comes with Laravel . It provides a number of useful commands to help you build your application. To view a list of all available Artisan commands, you can use the command:
1 2 | php artisan list |
We can create models and controllers using the following Artisan commands:
1 2 3 4 5 | php artisan make:model modelName php artisan make:controller controllerName |
But how to create 1 View & Blade Templates with Artisan like below?
1 2 3 | php artisan make:view |
At a glance, there is an Artisan View package to handle this. But we want to create an Artisan Console like that, how to do it?
This article will guide you how to create Blade Template through the Artisan Console . php artisan make:view
2.Get started
- Create Commands: MakeView
php artisan make:command MakeView
- Logic code that creates the view1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374namespace AppConsoleCommands;use IlluminateConsoleCommand;use File;class MakeView extends Command{/*** The name and signature of the console command.** @var string*/protected $signature = 'make:view {view}';/*** The console command description.** @var string*/protected $description = 'Create a new blade template.';/*** Execute the console command.** @return mixed*/public function handle(){$view = $this->argument('view');$path = $this->viewPath($view);$this->createDir($path);if (File::exists($path)) {$this->error("View {$path} already exists!");return;}File::put($path, $path);$this->info("View {$path} created.");}/*** Get the view full path.** @param $view* @return string*/private function viewPath($view){$view = str_replace('.', '/', $view) . '.blade.php';return "resources/views/{$view}";}/*** Create view directory if not exists.** @param $path*/private function createDir($path){$dir = dirname($path);if (!file_exists($dir)) {mkdir($dir, 0777, true);}}}
- Registered in App / Console / Kernel1234protected $commands = [MakeView::class];
3.Test
- Create a home.blade.php view in the default directory
php artisan make:view home
- Create a view ‘home.blade.php’ in the sub-view (‘pages’)
php artisan make:view pages.home