Use Gulp to Start a Laravel PHP Server

Chris Sevilleja
👁️ 15,924 views
💬 comments

Today we'll be showing off a quick tip for making your Gulp files a little more useful.

When building out Laravel applications, if we are using PHP's built-in server, then we can start our applications using:


$ php artisan serve

This will start our Laravel server and let us develop.

Table of Contents

    laravel-artisan-serve

    We must usually also start up Gulp (whether we use Elixir or plain Gulp).

    Starting a PHP Server with Gulp

    Let's say we wanted to consolidate more commands into our Gulp file. There's just something cool about giving other users access to your project and giving them the following instructions:

    1. Clone/fork the repo
    2. Install dependencies (composer install and npm install)
    3. Start everything (gulp)

    Simple and easy.

    Luckily there's a neat npm package called gulp-connect-php.

    Using gulp-connect-php

    Start a new Laravel install using the Laravel CLI tools.

    
    $ laravel new site
    

    laravel-new-command

    Now we can grab all the packages that we need:

    
    $ cd site
    $ npm install gulp gulp-connect-php --save-dev
    

    With these packages, let's move into our gulpfile.js. Clear out what's in there currently (there will be some lines about elixir).

    The Task

    This is what our new gulpfile.js will look like:

    
    // grab all our packages
    var gulp = require('gulp'),
        php = require('gulp-connect-php');
    
    // create a task to serve the app
    gulp.task('serve', function() {
    
        // start the php server
        // make sure we use the public directory since this is Laravel
        php.server({
            base: './public'
        });
    
    });
    

    Now we can use this serve task.

    
    $ gulp serve
    

    laravel-gulp-connect-php-serve

    Note: If you run into any errors, make sure your Laravel installation is good to go. I had to create my .env file and create a new application key using php artisan key:generate to get this to work.

    Conclusion

    Just like that, with one simple package, we have given our gulpfile.js another job to help simplify our development lives.

    Chris Sevilleja

    176 posts

    Founder of Scotch.io. Google Developer Expert in Web Technologies. Slapping the keyboard until something good happens.