Is it possible to create custom npm run commands for Laravel?

3.1k Views Asked by At

Laravel has the following built-in npm run commands (among others):

npm run install
npm run watch

Is it possible to create custom npm run commands to run custom PHP scripts? For example, I want to create a command called npm run csv that will run a PHP script that imports a bunch of CSV data into a database.

Thanks.


Edit: After asking the question and seeing a lot of the responses, it has become overwhelming obvious that writing a php artisan command is probably the better way to go. As such, that's what I will do.

Thank you all for your responses. As for why I didn't ask that question, it's quite simple: I didn't know that that was a better approach. I'm still new to Laravel and learning. Thanks.

4

There are 4 best solutions below

5
On BEST ANSWER

At first, you must write Artisan Console Command. Then you could run it using npm. But this is not a recommended way. you can run any artisan command like:

php artisan inspire

If you want to run this with npm just add this command in the package.json's script. For example:

{
   "scripts": {
       "inspire": "php artisan inspire"
   }
}

Then run the command like this:

npm run inspire
0
On

There's no need to use NPM to call PHP! Why not just create your own executable?

Using Laravel, there is a command system, so you can make your own artisan commands. But if you want something simpler, you can do this:

Example. I create a file in my project called bin/do_stuff

#!/usr/bin/env php
<?php
      echo "Easy as that!\n";

Then make it executable:

chmod +x bin/do_stuff

Then you can run it with ./bin/do_stuff! Not hard at all! Now you can also pass arguments like so:

./bin/do_stuff--option1=value1 --option2

With or without values. To do this, we add the following:

foreach ($argv as $arg)
{
    preg_match('/\-\-(\w*)\=?(.+)?/', $arg, $value);
    if ($value && isset($value[1]) && $value[1])
    {
       $options[$value[1]] = isset($value[2]) ? $value[2] : null;
    }
}

Great for in cron jobs and back end stuff. Give it a try!

0
On

It should be cleaner to create your own artisan command.

See https://laravel.com/docs/5.7/artisan#writing-commands

Then put your csv import code inside the handle() method.

You will just have to run : php artisan import-csv or something like

0
On

I love this side of Laravel. From what you are trying to achieve, may I advise on custom artisan commands? :)

https://laravel.com/docs/5.7/artisan

Recommend the reading, it is great for what you are looking :D