Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to take a file as input in laravel artisan console?

I am working with a laravel application and I instead of inputting just arguments and options, I want to know if there is a way where I can input files. I wish to import a lot of data from other APIs and I am using Guzzle to do that.

A lot of the times the same data is being imported at each database reset. Which is why I imported the data in a json file collection first and then I use that collection every time to insert the data in the database which saves the time to fetch the data each time from the other API.

Right now I am hard coding the file which is used but is there a way where I can fetch the file via the command line where I specify the arguments and options for the console command?

like image 347
Rohan Avatar asked Aug 05 '16 08:08

Rohan


1 Answers

There are many ways you could do that.

One option would be to pass file path as command argument and then read the file using basic file_get_contents() function.

class YourCommand extends Command {
  public function fire() {
    dd(file_get_contents($this->argument('path'));
  }

  protected function getArguments()
  {
      return [['path', InputArgument::REQUIRED, "File path"]];
  }
}

You could also make use of Laravel's Filesystem Library and setup a local storage (see https://laravel.com/docs/5.1/filesystem for more details) and put the file in your storage/app folder:

class YourCommand extends Command {
  public function fire() {
    dd(Storage::get($this->argument('path')));
  }

  protected function getArguments()
  {
      return [['path', InputArgument::REQUIRED, "File path"]];
  }
}

If you want to avoid providing file path, the simplest way would be to just read the file from STDIN stream by retrieving the contents from the I/O stream:

class YourCommand extends Command {
  public function fire() {
    dd(file_get_contents('php://stdin'));
  }
}

You'd just need to run the command like the following:

php artisan yourcommand < file.json
like image 54
jedrzej.kurylo Avatar answered Nov 14 '22 23:11

jedrzej.kurylo