Wednesday, February 5, 2014

Creating a Laravel Project

Overview

So you've set up your server, installed all the pre-requisites, and have download your first Laravel project. Now what?

This tutorial is a quick overview of how to set up and configure a Laravel application.


Creating a Project

Just to review, we'll go over downloading the Laravel files again.

Open a command window in your wamp www folder.

In the command window, enter:

composer create-project laravel/laravel [project-name] --prefer-dist

Wait for the files to download.


Laravel Generators

Next we will install the Laravel Generators created by Jeffrey Way. These generators add commands to Artisan that helps you in creating Laravel components faster.

Check out the Laravel Generators Github project for more info

In your Laravel project folder open composer.json

Add a way/generators entry it to the require object. For example:

composer.json
"require": {
 "laravel/framework": "4.1.*",
 "way/generators":"dev-master"
},

Next you have to update Composer to download the new dependencies.

Open a command window in the project folder and enter:

composer update

This will download the new dependencies.

The last step is to add the Generators Service Provider to Laravel.

In your Laravel project folder, open the file [project-folder]\app\config\app.php

Find the providers array

Add Way\Generators\GeneratorsServiceProvider to the providers array

app\config\app.php
'providers' => array( 
 'Illuminate\Foundation\Providers\ArtisanServiceProvider',
 .
 .
 .
 'Way\Generators\GeneratorsServiceProvider', 
),

To see the new Artisan commands, open a command window and enter:

php artisan

The generator commands are the generate:* ones.

Composer require-dev

Since the generators will only be used during development, you can also add them to the require-dev object:

composer.json
"require": {
 "laravel/framework": "4.1.*"
},
"require-dev":{
 "way/generators":"dev-master"
},

NOTE: If you do this, remember to add the service provider to your development environment app.php config file.

If you add the service provider to your production config file, you will get an error when deploying since the generators won't de downloaded for the deployed app.


Setting up Environments

Next, you have to create different environments for your project. You can have as many environments as you want, but you should at least have a production and development environment.

The default environment for Laravel is the production environment, so let's create a development environment.

First, you need a way to tell Laravel which environment you're currently working in.

Open [project_folder]\bootstrap\start.php

Find the $env variable.

bootstrap/start.php
$env = $app->detectEnvironment(array(

 'local' => array('your-machine-name'),

));

We are going to return a closure that tells Laravel which environment we're in.

So, change the variable to look like this:

bootstrap/start.php
$env = $app->detectEnvironment( function()
{
 return getenv('LARA_ENV') ?: 'development';
});

So, when the server variable LARA_ENV is set, use it's value. If not, use the development environment.

Note: I call my dev environment 'development', but you can call it whatever you want.


Server Variables

We are setting our environment based on the server variable LARA_ENV, but how do I set this variable?

In your app's public folder there is a file called .htaccess. You can open this file and add the following:

SetEnv LARA_ENV production

For setting a variable within your PHP code you can use

putenv('LARA_ENV=production');

Now, if you want to access the server variables you can use:

getenv('LARA_ENV');

Obviously, for your development environment you won't be setting this variable.


Why do I need to set environments?

While you are developing your web app on your local PC, you'll have a certain set of configurations for your database, mail settings, debug settings, etc...

When deploying your app to the web, you'll require a different set of configurations. For example, while in development you'll require debug messages, but you wouldn't want them to show up in production.

Setting different environments in Laravel makes this process simple and automatic and you don't have to manually go change your configurations every time you deploy your app.


How do I check my environment?

In Laravel, you can see what the current environment is by using:

App::environment();

However you won't need to check your environment. The configuration files will automatically return the values for the correct environment.


Configuration Files

Next, we have to create our different configurations for the different environments.

Since the default is production, we'll only be creating files for the development environment.

In your app/config folder, create a new folder and call it development. (Or whatever you called your dev enviroment)

Now copy the files which will have different configurations for development into the folder.

You probably won't be changing every single config file, but here are some examples of what you might change:

app.php

Set debug => true for development. You'll also need different keys for development and production.


database.php

Different database connections for development and production.


mail.php

Email configuration. You'll probably have pretend => true for development.


Your own config file

If you have some values which you need throughout your app ( ex. api keys ), you don't need to put them in one of the existing config files. You can create your own config file and config array and access it like the normal configuration values.

Check through the different config files to see what you need to set up for your environments.

Remember, you don't have to replicate the entire file for different environments, only keep the values that you're changing.


How do I access config values?

You can access the config values anywhere in the app by using:

Config::get( '[file_name].[value_name]' );

So, for example, if you want to get the key value in the app.php file, you would use:

Config::get( 'app.key' );

One last thing before we're done with the configurations, if you copied a new app.php to your development environment, you're production and development environments now have the same encryption key.

You need to create a new key for the production environment.

Open a command window in the project folder.

Run the following command:

php artisan key:generate

Now your production environment and development environment should have different keys.


Creating Your Database

Now we have to create the database for the application. I'll be using mysql.

Creating the database

If wampserver is not running, run it now.

When the server is running, open a browser and go to : http://localhost/phpmyadmin/

Enter the username = root and the password is blank.

Select databases

Type the name of the database and for Collation choose: utf8_unicode_ci

You now have an empty database.


Setting up Laravel to use the Database

Open app/config/development/database.php. (The one you created when setting up your environments.)

Change the name of the database for mysql

app/config/development/database.php
'connections' => array(

 'mysql' => array(
  'driver'    => 'mysql',
  'host'      => 'localhost',
  'database'  => '[change to your database name]',
  'username'  => 'root',
  'password'  => '',
  'charset'   => 'utf8',
  'collation' => 'utf8_unicode_ci',
  'prefix'    => '',
 ),
),

The rest of the settings you can leave as is.

Since that's the only setting we'll be changing for the development environment, you can remove the other settings.

Remember not to deploy your app with a blank root password. That would be bad.


Your Application Folder

Instead of just putting all your files into the existing folders, you'll want to create and application folder where you can put your project files.

In your Laravel app folder, create a new folder with a name for your project.

So it would be:

[your_project_folder]\app\[your_app_folder]

This is where you'll place your providers, facades, repositories, utilities, etc.


Autoloading

PHP will not automatically include new files you create, so, in order to use the files you put in your new project folder, you need to autoload them using Composer.

In your root folder, open composer.json

In the autoload object, add the following:

composer.json
...
"autoload": {
 "classmap": [
  "app/commands",
  "app/controllers",
  "app/models",
  "app/database/migrations",
  "app/database/seeds",
  "app/tests/TestCase.php"
 ],
 "psr-4": {
  "[your_app_folder]\\": "app/[your_app_folder]"
 }  
},
...

Replace [your_app_folder] with the name you created above.

Finally, dump composer to generate new autoload info

In a command window in your project, enter:

composer dump-autoload -o

The -o is for optimization.

Files you create in your new project folder should now automatically be loaded.

Composer autoload

Whenever you add a folder to your app folder, you need to run composer dump-autoload -o.

So if php can't find a class you created, usually it means you need to dump-autoload.


Finishing Up

That's about all there is for setting up an application.

If you need to include additional files that are not classes, (example. filters, macros, helper functions) you can include them in your:

app\start\global.php file.

So, I want to create a file where I store some custom 'form macros'. I create the file and put it in app/MyApp/macros/FormMacros.php.

So, I can include the file by using the following line at the end of global.php

app/start/global.php
require app_path() . '/MyApp/macros/FormMacros.php';

That's it. All you have to do now is load your web app in your browser and start developing.


How do I access my application?

There are two ways to view your application in a browser. The Apache server or the Artisan server.

Apache Server

Make sure wamp is running

In the browser navigate to

http://localhost/[your_project_path]/public


Artisan Server

Open a command window in your project folder

Run the command

php artisan serve

In your browser navigate to

http://localhost:8000


Happy developing.


2 comments:

  1. Thank you for the overview. One question: Under "How do I access config values?" you show how to generate different encryption keys for the development and production environments. But any passwords in the database that were hashed using one key will not work with the other key, correct?

    ReplyDelete
    Replies
    1. The encryption keys aren't used for password hashing, so hashed passwords will work across all environments.

      Delete