Khizer Rashid
Khizer Rashid

Reputation: 146

How to Create Custom file and Write code programmatically in Laravel

I am working on a Laravel project in which I need to create custom blade view file programmatically and write some code as a placeholder. I have done most of the work i.e. I have created view file using custom command. But now I need to put some code as a placeholder at the time of creating view file. Here is my code

<?php
  
namespace App\Console\Commands;
  
use Illuminate\Console\Command;
use File;
  
class MakeViewCommand 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("File {$path} already exists!");
            return;
        }
  
        File::put($path, $path);
  
        $this->info("File {$path} created.");
    }
  
     /**
     * Get the view full path.
     *
     * @param string $view
     *
     * @return string
     */
    public function viewPath($view)
    {
        $view = str_replace('.', '/', $view) . '.blade.php';
  
        $path = "resources/views/{$view}";
  
        return $path;
    }
  
    /**
     * Create view directory if not exists.
     *
     * @param $path
     */
    public function createDir($path)
    {
        $dir = dirname($path);
  
        if (!file_exists($dir))
        {
            mkdir($dir, 0777, true);
        }
    }
}

As you can see the file is being created but how to put some code there. Any help would be highly appreciated.

Upvotes: 1

Views: 400

Answers (0)

Related Questions