Web Development using PHP and Laravel

Опубліковано: - Востаннє змінено:

PHP is the motor of the World Wide Web. Why? Because PHP was used to write Content Management Systems like Wordpress or create MVC frameworks like Zend Framework, CodeIgniter or Laravel. According to the PHP website, there were 244 million websites powered by PHP in 2013.

Laravel is the youngest of the mentioned frameworks, but it is very popular and rapidly adopted by developers. Laravel is a full MVC framework, offering validation, ORM, session management, template engine, HTML helpers and routing engine, it was built for developers.

I will present the Contact Card application (the one which I using Flask in Python), but this time I use Bootstrap and Laravel. Setting up Laravel development environment can be painful, you can reference Creating a Laravel Development Environment article for Laravel project and dev env creation. The application was created for demonstration purposes, so there are missing parts, like data validation, error handling and security features.

Contact Card Application main page

Laravel Project Structure

   laravel project folder structure

  1. app – this is the application folder where all the code (models, controller, views, configuration and migration) files are stored
  2. bootstrap – here are the files used by the Laravel framework to start the application 
  3. public – this folder contains the public files which are used by the project(like css files, images and JavaScript code)

The app’s folder

There are three “base” folders, models – holds all the classes for entities (in case you use Eloquent ORM, here should be all the entities stored). The controllers hold the logic of the app, like data load, transformation and views construction. The views folder contains the pages rendered by the Blade template engine (these have HTML and blade code).

   Laravel Project app folder directory structure

Routing engine inside Laravel

In the application I defined the following routes (file: app/routes.php)

Route::get('/', array( 
	'as' => 'welcome', 
	'uses'=>'ContactController@index'));

Route::get('/contacts', array( 
	'as'=>'contacts',
	'uses'=>'ContactController@showAll'));

Route::get('/contacts/add', array( 
	'as'=>'add_contacts',
	'uses'=>'ContactController@create'));
	
Route::post('/contacts/add', array( 
	'as'=>'add_contacts',
	'uses'=>'ContactController@store'));

These type of routes are called named routes in Laravel.

Models

In the project I only have one model, Contact. Since I used Eloquent, I had to write only three lines of code to build up the model:

<?php
class Contact extends Eloquent {
    protected $table = 'contacts';
}

It’s a simple PHP class which derives from Eloquent (class available in the Laravel). By default all models are mapped to a table which has the name of the class in plural. For example if you have a class with name Dog, Eloquent will look for a table called dogs.

The $table variable is special, using this you can explicitly map a class to a table. In this case the default Eloquent behaviour would work; I wanted to highlight this, since it can be a useful feature if you migrate older PHP code to Laravel.

Controllers

I have the ContactController defined, which implements all the logic for serving the requests. Methods from controllers can be passed to routes using the @ sign. Laravel Controllers can be generated using the php5 artisan controller:make [ControllerName] command.

Code of the ContactController (I removed some comments):

class ContactController extends \BaseController {

	public function index()
	{
		return View::make('index');
	}

	public function create()
	{
		return View::make('add_contact');
	}
	
	public function store()
	{
		$new_contact = new Contact;
		$new_contact->first_name = Input::get('first_name');
		$new_contact->last_name = Input::get('last_name');
		$new_contact->birthday = Input::get('birthday');
		$new_contact->email = Input::get('email');
		$new_contact->website = Input::get('website');
		$new_contact->work_phone = Input::get('work_phone');
		$new_contact->home_phone = Input::get('home_phone');
		$new_contact->mobile_phone = Input::get('mobile_phone');
		$new_contact->save();
		return Redirect::route('contacts');
	}

	public function showAll()
	{
		$all_contacts = Contact::all();
		return View::make('contacts')->with('all_contacts', $all_contacts);	
	}
}

The index() function creates a new instance of the “index” view. The create() method also returns a view (with name “add_contact”). The store() method has more logic. If you look at the routing, this method was set up to be invoked when there is a POST HTTP request sent to the server. POST requests are sent when you press Save Contact button on Add Contact screen:

Contact Card Application - Add Contact screen

All the values in the form are sent back to the server and can be accessed using the Input class. I create a new Contact and assign values received from the form and use the save() method of the entity and the data has been stored to the database. Easy, isn’t it? At the end of the method I redirect the user to the contacts route, which is mapped to the showAll() method of the controller.  In showAll(), all the contacts are loaded, using the Conctact::all(); the result is passed to the “contacts” view:

Contact Card Application - Contacts page

Views

As mentioned, Laravel uses the Blade template engine. The code of the Contacts screen:

@extends('layouts.main')
@section('content')

<h1> Contacts </h1>

<div class="panel panel-default">
  <!-- Default panel contents -->
  <div class="panel-heading">All contacts in the database</div>
  
  <!-- Table -->
  <table class="table">
	 <tr>
	   <th>First Name</th>
	   <th>Last Name</th>
	   <th>Birthday</th>
	   <th>Website</th>
	   <th>Email</th>
	   <th>Work Phone</th>
	   <th>Home Phone</th>
	   <th>Mobile Phone</th>
	   <th>ID</th>
	 </tr>
	 @foreach($all_contacts as $contact)
	   <tr>
	    	<td>{{{ $contact->first_name }}}</td>
	    	<td>{{{ $contact->last_name }}}</td>
	    	<td>{{{ $contact->birthday }}}</td>
	    	<td>{{{ $contact->website }}}</td>
	    	<td>{{{ $contact->email }}}</td>
	    	<td>{{{ $contact->work_phone }}}</td>
	    	<td>{{{ $contact->home_phone }}}</td>
	    	<td>{{{ $contact->mobile_phone }}}</td>
	    	<td>{{{ $contact->id }}}</td>
	    </tr>
	@endforeach
	
  </table>
</div>
@stop

The screen extends the app/views/layouts/main.blade.php file. The main layout has a content section, here I override the content. I defined a HTML table where I display all the values from the database, each column showing a property of a contact. Using the @foreach blade syntax I iterate over the data sent from the controller ($all_contacts) and I create a row in the table for each contact. The {{{…}}} accesses the value of the expression inside AND it escapes all characters. This means if you use {{{…}}} format then you are saved from Cross Site Scripting attacks.

The @foreach blade command has to be closed using @endforeach and the @section ending can be specified using the @stop command.

The project is hosted on GitHub.

Опубліковано 20 січня, 2015

Greg Bogdan

Software Engineer, Blogger, Tech Enthusiast

I am a Software Engineer with over 7 years of experience in different domains(ERP, Financial Products and Alerting Systems). My main expertise is .NET, Java, Python and JavaScript. I like technical writing and have good experience in creating tutorials and how to technical articles. I am passionate about technology and I love what I do and I always intend to 100% fulfill the project which I am ...

Наступна стаття

Creating a Laravel Development Environment