Create dynamic view...

Create dynamic view in Laravel 10 , create custom artisan command using Laravel 10

Posted: 03 January 2025

Hello developers in this tutorial we will discuss about how to create custom artisan command and how to create dynamic view in laravel

What are Artisan commands?

Artisan commands are similar to commands on CMD or commands which we enter in terminal to make changes, Laravel comes with an inbuilt command line interface that name is Artisan, by the use artisan command we can make jobs, model, controller, migration and many more with the artisan command

Create new artisan command for view

For creating new custom artisan for creating view  , simply open the terminal and hit the below command with respective to file name.
Copy for creating artisan command

php artisan make:command createViewFile

Inside app/console/Commands/  you can see createViewFile.php 

Code for command view file

createViewFile.php code: 

<?php
 
namespace App\Console\Commands;
 
use Illuminate\Console\Command;
use File;
 
class createViewFile 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 view file';
 
    /**
     * Execute the console command.
     */
    public function handle()
    {
        $viewname = $this->argument('view');
 
        $viewname = $viewname.'.blade.php';
 
        $pathname = "resources/views/{$viewname}";
 
        if(File::exists($pathname)){
            $this->error("file {$pathname} is already exist " );
            return;
        }
        $dir = dirname($pathname);
        if(!file_exists($dir))
        {
          mkdir($dir,0777,true);
        }
 
        $content = '<!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
        </head>
        <body>
           
        </body>
        </html>';
 
        File::put($pathname , $content);
 
        $this->info("File {$pathname} is created");
       
    }
}

Here  protected $signature = 'make:view {view}';  represents how to start this command and {view} means what should be name of our view file after that in handle() function consist of main logic behind the command to be executable.

Entering artisan command

php artisan make:view front/aboutUs