Laravel 4: quick tutorial

Installation

Minimal requirements: PHP 5.3.7 with mcrypt and curl extensions

  • install Composer (used by Laravel to manage dependencies)
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
  • install Laravel installer
curl -O http://laravel.com/laravel.phar
chmod 777 laravel.phar
sudo mv laravel.phar /usr/local/bin/laravel
  • create a Laravel project in your web folder
laravel new blog

In case you get “Error in exception handler”:

chmod -R 777 blog/app/storage

Note: in production, the public folder should be the root of the website.

Configuration

In app/config/app.php:

  • turn on debug to see full stack traces when errors happen
       'debug' => true,

Routes and controllers

  • add a new route in apps/routes.php
Route::controller('article', 'ArticleController');

This will direct requests starting with ”/article” to ArticleController. Ex: /article, /article/complete-list

  • create the controller apps/controllers/ArticleController.php
<?php
 
class ArticleController extends BaseController {
 
    public function getIndex()
    {
        echo "index";
    }
 
    public function getCompleteList()
    {
        echo "complete list";
    }
}

Test it's working:

Note: the “get” prefix in the function name refers to the HTTP “GET” method. A function processing a form submission would be prefixed by “post”: postProcessForm().

Views

  • In apps/controllers/ArticleController.php, update getCompleteList()
public function getCompleteList()
{
	// create data array
	$data = array();
	$data['total'] = 13;
 
	// pass data to view
	$view = View::make('completeList', $data);
 
	return $view;
}
  • Create app/views/completeList.blade.php
<h1>Complete List</h1>
<p>We have {{$total}} articles.</p>

Note: the .blade.php extension is necessary to interpret $total in the view.

Templates

Create app/views/templates/main.blade.php

 <html>
     <body>
         @yield('content')
 
         @section('footer')
             <p>Some default intro text.</p>
         @show
     </body>
 </html>

Update app/views/completeList.blade.php

@extends('templates.main')
 
@section('content')
    <h1>Complete List</h1>
    <p>We have {{$total}} articles.</p>
@stop
 
@section('footer')
    @parent
 
    <p>This is appended to the default footer.</p>
@stop

Models

Database configuration

Update the database settings in app/config/database.php

         'mysql' => array(
             'driver'    => 'mysql',
             'host'      => 'localhost',
             'database'  => 'my_database',
             'username'  => 'root',
             'password'  => '123456',

Database table

We will use a migration to create a table for our articles. From the project root, run in the terminal:

php artisan migrate:make create_articles_table

Open the generated file in app/database/migrations and update its up() and down() methods:

public function up()
{
	Schema::create('articles', function($table)
	    {
	        $table->increments('id');
	        $table->string('title')->unique();
	        $table->string('body');
	        $table->timestamps();
	    });
}
 
public function down()
{
	Schema::drop('articles');
}

In the terminal:

php artisan migrate

The articles table has been created in the database.

Model class

Create app/models/Article.php

<?php
 
class Article extends Eloquent {
    protected $guarded = array('id');
}

Insert

In app/controllers/ArticleController.php, add getCreateArticle():

     public function getCreateArticle() {
     	// article data
     	$data = array();
     	$data['title'] = 'Title ' . rand();
 
     	// create article in database
     	$article = Article::create($data);
 
     	// display article title
     	echo "Created article: " . $article['title'];
     }

Load http://localhost/blog/public/article/create-article a few times to create a few articles.

Notes:

  • Eloquent is Laravel's ORM
  • $guarded in the model lists the not-modifiable fields when creating/updating an article:
// this would have no effect on the id of the article
$data['id'] = 43;

Select

In app/controllers/ArticleController.php, update getCompleteList():

     public function getCompleteList()
     {
         $data = array();
         $data['articles'] = Article::all();;
         $view = View::make('completeList', $data);
         return $view;
     }

Update app/views/completeList.blade.php to display the articles:

 @extends('templates.main')
 
 @section('content')
     <h1>Complete List</h1>
     @foreach($articles as $article)
         <p>{{ $article->title }}</p>
     @endforeach
 @stop

For more info, see Eloquent's documentation.

Reference

Feedback