Creating a Website Using Laravel 5 Part 1: Elixir and Assets

Creating a Website Using Laravel 5 Part 1
Laravel 5 Website Tutorial Screenshot

In this Laravel 5 tutorial series, we will create a full-fledged, Ajax powered, content sharing website. Our web application will allow its users to post links to their content, like others’ content, comment on others’ content etc. There will be an administration panel for the site administrators, that will allow them to perform operations like create/block users, create new categories, edit, delete user’s posted links when needed and many more. All the users of our application will have a home page from where they will be able to track and perform CRUD operations on their shared links and comments.

Please note that, the prior knowledge and understanding of the following frameworks/libs/languages is required for this tutorial:

  • PHP
  • Laravel 5/4
  • JavaScript
  • jQuery
  • Bootstrap

So, let us get started.

Installation and Setting up Laravel 5

Laravel’s official website describes a couple of methods for the installation of Laravel. We will use the first method i.e. the Laravel Installer method. This requires us to have Composer installed. If you don’t have Composer installed on your system. You can use the following commands to install the Composer globally on your OS ( Linux is assumed ).

$ mkdir ~/tmp
$ cd ~/tmp
$ curl -sS https://getcomposer.org/installer | php
$ sudo mv composer.phar /usr/local/bin/composer

After running the above commands you will have Composer installed globally. Next we need to get a copy of Laravel Installer, this requires us to run the following command inside the terminal:

$ composer global require "laravel/installer=~1.1"

Now we need to set the PATH variable so that we can run the installer by simply typing laravel inside the terminal. Add the following line at the end of your .bashrc file:

export PATH=~/.composer/vendor/bin:$PATH

Change the directory to your preferred location and run the following commands to install a copy of Laravel:

$ laravel new L5App
$ cd L5App
$ chmod +x artisan

After the successful completion of above commands you can serve the Laravel application by running the ./artisan serve command inside the L5App directory.

The .env File

In Laravel 5 all the configurations and environment specific settings have been centralized to one location i.e. the .env file. When the framework boots up it searches for the .env file inside the root path of the installation and populates the $_ENV and $_SERVER variables for the current PHP process. In addition to this, the files inside the config directory use the environment to populate the application level settings e.g. database settings, session driver settings, queue drivers etc.

Laravel 5 provides us with an example .env file that can be used as a starting point. The contents of this file are shown below:

APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomString

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

CACHE_DRIVER=file
SESSION_DRIVER=file

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null

Creating a Database

Let us drop to the terminal again and quickly create a database for our application:

$ mysql -u root -p
Enter password: 
mysql> create database L5App;
Query OK, 1 row affected (0.00 sec)

After creating the database, rename the .env.example file as .env and specify your database credentials. You can verify the environment settings by running the dd($_ENV) inside the tinker REPL ( read-eval-print-loop ).

Quick Tip:
We use the artisan key:generate command to generate the secret key for the application.

Setting up Elixir, Bootstrap, Font-awesome etc

Manipulating front-end resources / assets and performing tasks like script minification, preprocessing CSS, concatenating scripts and style sheets can be boring and cumbersome. Thanks to gulp and alike, this is no longer the case. These tasks can be performed in an automated way, resources can be watched for changes and tasks can be run accordingly. Elixir, written around gulp provides us with an easy and clean API that can be used to perform all aforementioned tasks. It does not matter if you are not familiar with gulp, no prior knowledge of gulp is required for using the Elixir.

In this section we will setup the Elixir and install the various front-end dependencies such as: Bootstrap, Awesome fonts, jQuery etc. We will see how we can use Elixir for compiling a theme for the bootstrap that we will use for our application’s interface.

I will assume that Node.js is installed on your system. If you don’t have a working installation, you can refer to the Node’s installation page.

Since Elixir uses gulp, we need to install it first. Open a terminal and run the following command:

$ npm install --global gulp bower

We will use bower for installing the front-end dependencies like Bootstrap, jQuery etc.

Now inside your Laravel 5 installation directory, execute the following command:

$ npm install

After the successful completion of the above command, Elixir will be installed along with its dependencies.

Bower for Front-end Dependencies

Bower without doubt is the most popular front-end dependency manager. Bower allows us to manage the application’s front-end dependencies in a declarative way. Also, it makes it easier to version control the application without worrying about the packages it requires i.e. there is no need to commit the dependencies to version control system. This is done using a special file called bower.json that holds the project’s dependency specifications. Other people, who will grab the application can pull the packages back by just running the bower install command.

The bower.json file for our project looks like this:

//location: L5App/bower.json
{
  "name": "L5App",
  "description": "Laravel 5 website tutorial",
  "license": "MIT",
  "private": true,
  "dependencies": {
    "bootstrap": "~3.3.2",
    "bootstrap-select": "~1.6.4",
    "font-awesome": "~4.3.0"
  }
}

By default bower creates the bower_components directory to hold the installed dependencies inside the current working directory. This behavior can be changed by specifying a general installation directory in a .bowerrc file. I will change the path so that all the installed dependencies should reside inside the L5App/resources/assets/vendor directory.

The .bowerrc file:

//location: L5App/.bowerrc
{
  "directory": "resources/assets/vendor"
}

You will need to add the above path inside your project’s .gitignore file as well.

Please remove the redundant resources/assets/less/bootstrap directory. It is no longer required.

Now, running the bower install command inside the project’s root i.e. L5App will install all the packages that are specified inside the bower.json file. After the completion of the above command you will have an assets directory similar to the one shown below:

┌─[usm4n@usm4n-desktop]―[~/Public/L5App/resources/assets ⎇  master #%]
└─•tree -L 2
.
│
├── less
│   └── app.less
└── vendor
    ├── bootstrap
    ├── bootstrap-select
    ├── font-awesome
    └── jquery

7 directories, 3 files

Compiling the Bootstrap Theme and Publishing Assets

Elixir utilizes the gulpfile.js to execute its tasks. Laravel 5 by default, provides us with a copy of this file. The following code snippet shows the default contents of this file:

//file: L5App/gulpfile.js

var elixir = require('laravel-elixir');

elixir(function(mix) {
    mix.less('app.less');
});

The above code specifies a single Elixir task i.e. compile the LESS source of the app.less file. By default Elixir’s less task assumes the path as resources/assets/less. So in this case, the specified task will compile the resources/assets/less/app.less file.

We use gulp command to execute elixir tasks.

A list of common Elixir tasks:

  • less(src, output, options)– compiles the less sources provided as src and copies the generated css to output dir. Search paths can be parovided as options argument.
  • sass(src, output, options)– compiles the sass sources.
  • styles(styles, output, baseDir)– combines the styles provided as styles array, by using the baseDir we can specify the base path for the styles.
  • scripts(scripts, output, baseDir)– combines the scripts provided as the scripts array.
  • copy(srcFile, destFile)– copies the srcFile to destFile. We can also copy the entire directories by specifying the directory paths.

For our application, we will use one master CSS file i.e. app.css, which will contain all the compiled CSS from the LESS sources of bootstrap, bootstrap-select and font-awesome packages. In order to change the outlook of the bootstrap components, we will override the bootstrap variables using our own implementation of the variables.less file. For javascripts, we will use two files: a vendor.js file and app.js file ( please create the app.js file inside the resources/assets/js/ directory ). We will combine the javascripts from jQuery, bootstrap and bootstrap-select packages as vendor.js. All the application’s JavaScript will go inside the app.js file.

Quick Tip:
Running gulp command on every single change is not very practical. Fortunately, we can use the gulp watch command to track any changes in assets and run the tasks automatically. We will use this command when writing application’s JavaScript.

Now download this gist, extract it and save the solarized.less file inside the L5App/resouces/assets/less directory. Next open the L5App/resources/assets/less/app.less file and replace its contents with the following code:

//file: L5App/resources/assets/less/app.less

@import "font-awesome";
@import "bootstrap";

//variable overrides
@import "solarized";

@import "bootstrap-select";

Finally let us specify our intended tasks inside the L5App/gulpfile.js:

//file: L5App/gulpfile.js

var elixir = require('laravel-elixir');

var bowerDir = './resources/assets/vendor/';

var lessPaths = [
    bowerDir + "bootstrap/less",
    bowerDir + "font-awesome/less",
    bowerDir + "bootstrap-select/less"
];

elixir(function(mix) {
    mix.less('app.less', 'public/css', { paths: lessPaths })
        .scripts([
            'jquery/dist/jquery.min.js',
            'bootstrap/dist/js/bootstrap.min.js',
            'bootstrap-select/dist/js/bootstrap-select.min.js'
            ], 'public/js/vendor.js', bowerDir)
        .copy('resources/assets/js/app.js', 'public/js/app.js')
        .copy(bowerDir + 'font-awesome/fonts', 'public/fonts');

});

Since we want the bootstrap and the company to be compiled from the vendor directory. The path of this directory is specified on the second line of the above code. Next an array of paths to the LESS resources is declared. The first task specifies that, compile the app.less file by using the paths provided inside the lessPaths array and place the final compiled CSS file ( app.css ) inside the L5App/public/css directory. The next task will combine all the JavaScript files from the specified paths into public/js/vendor.js file. Similarly fonts are copied to their respective public directory.

Now after running the gulp command inside the root of the application, you will have a public directory like this:

┌─[usm4n@usm4n-desktop]―[~/Public/L5App/public ⎇  master #%]
└─•tree -L 2
.
├── css
│   ├── app.css
│   └── app.css.map
├── favicon.ico
├── fonts
│   ├── FontAwesome.otf
│   ├── fontawesome-webfont.eot
│   ├── fontawesome-webfont.svg
│   ├── fontawesome-webfont.ttf
│   ├── fontawesome-webfont.woff
│   └── fontawesome-webfont.woff2
├── index.php
├── js
│   ├── app.js
│   ├── vendor.js
│   └── vendor.js.map
└── robots.txt

3 directories, 19 files

What is Next?

In the next part of this tutorial, we will create the database schema and define the models and their relationships.

11 thoughts on “Creating a Website Using Laravel 5 Part 1: Elixir and Assets”

  1. I’m just trying to reproduce your steps, and It seems that it all works. You added solarized.less file to your resources/assets/less folder, but you didn’t add path to lessPaths in gulpfile.js . Now I’m trying to make some changes (like change color of navbar) in solarized.less, but nothing changes. Even when I comment out the @import ‘solarized’ in app.less nothing changes. Am I doing something wrong?

    1. Yes, I did not add the path inside the lessPaths, becasue I had already included it inside the app.less file i.e @include "solarized"; and both files are in the same directory. And for your changes to be compiled, you need to re-run the gulp command or use the gulp watch command. I have just tested it by changing the @navbar-default-bg variable and it works fine.

      Usman.

  2. I am trying to mix 2 separate less files: front and backend and I am doing something like

    mix.less([‘front-style.less’,’admin-style.less’], [‘public/css’,’public/css’], { paths: lessPaths }) but it is not working. do you have any ideea how could I do that?

    Thanks

    1. It has been fixed in the latest version of elixir, now you can do something like mix.less('file1.less','output_path').less('file2.less','output_path');. Just update your elixir installation npm update.

      Usman.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.