DEV Community

Cover image for Running Laravel Development Server and NPM in One Command
Chabba Saad
Chabba Saad

Posted on

Running Laravel Development Server and NPM in One Command

Managing a modern Laravel project often involves running multiple commands to start the development environment. Typically, you need to run php artisan serve to start the Laravel development server and npm run dev to compile your frontend assets. To streamline this process, you can create a custom Artisan command that runs both commands simultaneously. In this article, we'll walk through the steps to create this command in Laravel.

Creating the ServeAndDev Command

First, let's create a new Artisan command called ServeAndDev. This command will start both the Laravel development server and the NPM build process in separate processes.

php artisan make:command ServeAndDev

Step 1: Define the Command

In your Laravel application, navigate to the app/Console/Commands directory and create a new file named ServeAndDev.php. Add the following code to this file:

<?php
namespace App\Console\Commands;

use Illuminate\Console\Command;

class ServeAndDev extends Command
{
    // Define the command signature and description
    protected $signature = 'serve:dev';
    protected $description = 'Run php artisan serve and npm run dev';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Run php artisan serve in a separate process
        $this->info('Starting Laravel development server...');
        $serveProcess = popen('php artisan serve', 'r');

        if ($serveProcess) {
            $this->info('Laravel development server started.');

            // Run npm run dev in a separate process
            $this->info('Starting npm run dev...');
            $npmProcess = popen('npm run dev', 'r');

            if ($npmProcess) {
                $this->info('npm run dev started.');
            } else {
                $this->error('Failed to start npm run dev.');
            }
        } else {
            $this->error('Failed to start Laravel development server.');
        }

        // Keep the command running
        while (!feof($serveProcess) && !feof($npmProcess)) {
            echo fgets($serveProcess);
            echo fgets($npmProcess);
        }

        pclose($serveProcess);
        pclose($npmProcess);
    }
}

Enter fullscreen mode Exit fullscreen mode

in laravel 11 no need to register the command

Step 3: Running the Command
With the command defined and registered, you can now run it using Artisan. In your terminal, simply execute:

php artisan serve:dev

Top comments (4)

Collapse
 
hichamde profile image
HICHAM IAMIRI

Amazing.

Collapse
 
chabbasaad profile image
Chabba Saad

thank you Hicham <3

Collapse
 
costoo_f037c9dfc3227e0d0d profile image
costoo

nice

Collapse
 
chabbasaad profile image
Chabba Saad

thank you