DEV Community

Cover image for Create Laravel artisan commands and test database
Md. Morshadun Nur
Md. Morshadun Nur

Posted on

Create Laravel artisan commands and test database

I'm going to use Artisan command line interface to create custom command. For this you can can run

php artisan make:test CreateTestDatabase

Now, you go to this directory app/console/commands and open the CreateDatabase.php file.

  1. Initialise the $fileSystem variable and define the command name.
protected $signature = 'testdb:create';

protected $description = 'Create test database sqlite';

private $fileSystem;
Enter fullscreen mode Exit fullscreen mode
  1. Set the Storage factory in constructor Illuminate\Contracts\Filesystem\Factory
parent::__construct();
$this->fileSystem = $storage->disk('public'); 
Enter fullscreen mode Exit fullscreen mode
  1. Now create the database.sqlite file in the database directory and run the migration command.
public function handle()
    {
        if (!file_exists(base_path('database/database.sqlite'))){
            $handle = fopen(base_path('database/database.sqlite'), 'c');
            fclose($handle);
        }

        $this->fileSystem->put('database.sqlite', '');
        $this->call('migrate', [
            '--database' => 'sqlite'
        ]);
    }
Enter fullscreen mode Exit fullscreen mode

So, now I can run the command php artisan testdb:create in the terminal and it will create the sqlite file and run the database migrations automatically.

Full code is given bellow -

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Contracts\Filesystem\Factory;

class CreateTestDatabase extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'testdb:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create test database sqlite';

    private $fileSystem;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(Factory $storage)
    {
        parent::__construct();
        $this->fileSystem = $storage->disk('public');
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        if (!file_exists(base_path('database/database.sqlite'))){
            $handle = fopen(base_path('database/database.sqlite'), 'c');
            fclose($handle);
        }

        $this->fileSystem->put('database.sqlite', '');
        $this->call('migrate', [
            '--database' => 'sqlite'
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Thank you so much for the reading. <3

Top comments (0)