Getting Started with Laravel on Nitrous.io

Tweet

On February 12th, Nitrous.IO, the cloud development environment that lets you set up virtual boxes in a flash and use them from whichever platform through their Web IDE, finally added PHP support – something users have been clamoring for.

You can read more about it in the announcement, but I figure it’s best if we demo by example and get a Laravel app up and running.

Note: This tutorial assumes basic Unix terminal proficiency.

Getting started

Create an account on Nitrous.io if you don’t have one yet, or follow my ref link here to do so (full disclosure, this gives me nitrous – the currency used to bring more powerful VMs online). After spiffying up your profile, I encourage you to go into Public Keys and add a public SSH key of your own if you generally use them for SSH connections and similar. A detailed guide is available on GitHub.

Creating a box

Let’s go into Boxes and click “New Box”. Select PHP, a region closest to you, and allocate as many resources as you wish – you can spend your entire Nitrous balance on this if you so choose – when you terminate a box, your nitrous is refunded.

After clicking Create Box, your box will be provisioned – not unlike with Vagrant. You just won’t see as much output, and it’ll be much faster.

Once done, you’ll be greeted with a friendly and vaguely familiar interface, along with an introductory file that guides you through setting up the rest.

You can also run a PHP box by using any other template, and then using the Autoparts -> Install Parts menu to install PHP related tools like Apache, PHP, MySQL, etc. In the PHP box template, those parts are included. If you now use the included console to output the PHP version, you should see 5.5.8 displayed:

“Parts” is something like Nitrous’ custom tailored package manager, and you use it to start services and install parts. Parts can also automatically install WordPress for you, but who would want that anyway?

PhpInfo

Open the workspace folder, and create a file called index.php in the www subfolder with the contents:

<?php
    phpinfo();

Then, go to Preview -> Port 3000 (the default). You should see the following PhpInfo screen in your browser:

Note that the other ports won’t work unless you configure them that way. The first one (3000 SSL) is a premium feature, and you’ll have to pay for it, while all others can be defined if you use the console to edit httpd.conf:

vim /home/action/.parts/etc/apache2/httpd.conf

Note that you can access these files through the file browser as well, just remember to click “Show Hidden” at the bottom of the file browser. I find it simpler to go through the command line, though.

Installing PECL libs

Composer needs the Zip library to work, and installing it on our box is very simple, as per instructions

pear config-set php_ini /home/action/.parts/etc/php5/php.ini
pecl config-set php_ini /home/action/.parts/etc/php5/php.ini     
pecl install zip

To paste in the console, remember to press CTRL + SHIFT + V instead of just CTRL + V. Building and installing might take a couple minutes, wait it out.

But having a www folder is so early 2000s. Almost smells of a shared host, doesn’t it? Let’s pro it up.

Configure a Virtual Host

There are two paths you can take here. One is defining multiple virtual hosts, as is common with Apache. The other is renaming the www folder to public and using the workspace folder as our app’s folder. I’m not a fan of the latter, because it imposes some limits on my pre-built apps, so let’s go with the former.

Once again, vim into httpd.conf: vim /home/action/.parts/etc/apache2/httpd.conf

At the bottom of the file, add the following block:

<VirtualHost *:4000>
    ServerName doesnotmatter
    DocumentRoot "/home/action/workspace/myapp/public"
    ServerAdmin bruno.skvorc@sitepoint.com
        <Directory "/home/action/workspace/myapp/public">
            Options Indexes FollowSymLinks
            AllowOverride All 
            Require all granted
            Order allow,deny
            Allow from all
        </Directory>
</VirtualHost>

Literally, add it to the end of the httpd.conf file:

Additionally, at the top of the file where it says Listen 0.0.0.0:3000, you should add another line: Listen 0.0.0.0:4000. Do this for every port you want listened to.

An alternative is putting all this into the config subfolder as the comment near the top of the httpd.conf file says. Pick your poison, either works.

Now create the folder mentioned in this configuration.

mkdir -p /home/action/workspace/myapp/public

The -p parameter forces a recursive creation, meaning it creates all parent folders as well. Now add the same index.php file with the phpinfo(); content into this folder. A shorthand command to do it is this:

cd /home/action/workspace/myapp/public/
echo "<?php phpinfo();" > index.php

Restart Apache with parts restart apache2 and try opening the site on port 4000 via Preview -> Port 4000. You should see the same PhpInfo screen as before.

You can set up other virtual hosts in the same way.

Installing Composer

Update: Note that Composer is now pre-installed, and you can skip this step. Still, this part covers installing of custom binaries, so you might want to read it nonetheless.

Now that we got virtual hosts out of the way and can run several apps under one box if we so choose, let’s install Composer. We’ll be installing it globally – installing it once in every app makes absolutely no sense, especially on boxes with such limited hard drive space.

Nitrous.io boxes are limited in that you cannot create folders outside your home folder. To get around this limitation, we’ll just install it into a folder inside our home folder, and add said folder to the $PATH.

mkdir ~/.tools
cd ~/.tools
curl -sS https://getcomposer.org/installer | php
vim ~/.bashrc

Once vimmed, edit .bashrc by adding the following to the end of it:

export PATH=$PATH:$HOME/.tools/

Then, reload the .bashrc file by executing source ~/.bashrc.

With that, Composer has been globally installed and you can use it from whichever app you want. Try it out by executing the following commands:

cd /home/action/workspace/myapp
composer self-update

Creating a sample Laravel app

Composer, check. Virtual host, check. Let’s fire up Laravel, shall we? FYI, I chose Composer as the method of Laravel installation because it’s useful for much more than just Laravel, and you’ll eventually be needing it for other non-Laravel projects too.

First, let’s remove the myapp folder. Composer won’t create a project in a folder that’s not empty, so this will allow it to start from scratch.

rm -rf /home/action/workspace/myapp

Then, initiate the create-project command:

cd /home/action/workspace
composer create-project laravel/laravel myapp --prefer-dist

After a minute or two, everything should be downloaded. Visiting the same 4000 port on our box should give us the Laravel greeting screen.

Following the Quick Start Instructions, we add a closure route to /test by adding the following content to app/routes.php:

Route::get('test', function()
{
    return 'Test!';
});

Now, visiting {$URL}:4000/test gives us the following output:

Connecting Laravel to MySQL

Let’s first check if our database works. Try punching in mysql -u root into the Nitrous command line, and see if you get in. If you can list databases with SHOW DATABASES;, change database to test with USE test; and then list tables in that database with SHOW TABLES; (result should be an empty set), you’re ready.

Laravel is, by default, configured to use the same insecure settings Nitrous uses – database username “root” with no password. As such, the connection is ready by default – all you need to do is change the database name in the config file to “sample”, as that is the one we’ll be using in the following example.

You should, naturally, change your credentials – in MySQL, add a user that’s only allowed to mess with a specific database, and add that user into the app/config/database.php file in the appropriate section. For user-based database privileges, read this answer. We won’t be doing that just for the purpose of this demo.

We could follow the Migration example in the quick start doc, but I’d rather do it all in one go and have our sample data ready instantly. To create a sample database with a test table and three rows of sample values, execute the following command in the Nitrous console, regardless of the folder you’re currently in:

wget -O- -q https://gist.github.com/Swader/8994154/raw/9bb8d253f92791de77fa01138febd404a306ccc6/sample.sql | mysql -u root

What this does, if you’re curious, is fetch my gist with the SQL code required to make it happen, outputs it to the standard output stream in the shell while silencing all errors and other log info, and applies it to MySQL after logging in as root.

We won’t be building a model just for the test data – I assume you can follow the extremely simple instructions on the Laravel page to make that happen yourself. Instead, we’ll just be demonstrating Laravel’s ability to connect to the database here.

In the routes file from before, replace our previously written closure with the following:

Route::get('test', function()
{
  var_dump(DB::select('select * from test'));
});

Refreshing the /test URL, we get the database output:

Conclusion

This article proved how simple it is to get a Laravel configuration up and running on Nitrous.io. Play around, look at the documentation, try to break things. If you do, just terminate and recreate the box – it’s that simple.

We’re in an age of virtual machines at every step, and our hardware and bandwidth are powerful enough to prevent us from polluting our main desktop environments with needless installations. Experiment without fear and let us know what you come up with, we’d love to take a look.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Open PHPeter

    Hi,

    Turns out that the PHP Box at nitrous has already composer pre-installed. So you don’t have to install it. I have also written a (ok, very small) how-to for Laravel on nitrous.io. You can find it here: http://phpeter.tumblr.com/post/76516412240/laravel-in-under-5-minutes

    Regards, phpeter

    • http://www.bitfalls.com/ Bruno Skvorc

      Hm, didn’t have it when I first tried. At least I don’t think it did. Thanks for the heads up.

      • dylan prior

        Pretty sure it happened on the 15th feb, They probably saw you putting this together. Always the way. Thanks for the tutorial tho. Much appreciated.

  • http://quran.2index.net/ Said Bakr

    It should be `parts restart apache2` bash does not able to find apache. Also I suggest to use pico instead of vim.

    • http://www.bitfalls.com/ Bruno Skvorc

      Thanks for the heads up, fixed!
      The editor is a personal preference. I’m used to vim, but by all means, use whatever you like more.

  • http://heera.it/ Sheikh Heera

    Can I think this as another GUI based Vagrant that lives on the cloud ?

    • http://www.bitfalls.com/ Bruno Skvorc

      Pretty much.

  • http://johnveldboom.com/ John Veldboom

    Do you know if it’s possible to install the PHP curl functions? I was going to test some queues but was not able to get the curl_init() function to work. Tried “sudo apt-get php5-curl” but it looks like that’s being blocked.

    • http://www.bitfalls.com/ Bruno Skvorc

      It is, yes. Custom extensions can be installed easily, and a new article targeting that exact procedure step by step is coming soon. Here’s a spoiler: download PHP’s source code, enter the ext/curl subfolder, run “phpize; ./configure –with-curl; make; make install” and you’re good to go after you add it to php.ini.

  • Tyler Youschak

    Hi. When I follow this tutorial and run “pear config-set php_ini /home/action/.parts/etc/php5/php.ini”, I get pear: command not found. Help would be appreciated, thank you!

    • http://www.bitfalls.com/ Bruno Skvorc

      Pear is (or should be) automatically installed in every PHP box. Did you run the PHP box template? If not, try building a PHP box. If you did, try destroying it and starting from scratch.

      • Tyler Youschak

        Thanks for your fast response! I did use the PHP box template. I have just recreated the box and I am still getting the pear: command not found.

      • Tyler Youschak

        I actually tried not doing that step since composer is already installed on the server and it composer still worked.