Nothing Special   »   [go: up one dir, main page]

Learn Laravel in 1 Week: Devan Singaram

Download as pdf or txt
Download as pdf or txt
You are on page 1of 35

Learn laravel in 1 week

A social initiative by TribeHired.com for craftsmen

Devan Singaram
Learn laravel in 1 week
A social initiative by TribeHired.com for craftsmen

Devan Singaram
This book is for sale at http://leanpub.com/leanlaravel

This version was published on 2015-05-07

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.

©2015 TribeHired.com
Tweet This Book!
Please help Devan Singaram by spreading the word about this book on Twitter!
The suggested tweet for this book is:
I just downloaded a draft copy of lean laravel in 1 week
The suggested hashtag for this book is #tribehired.
Find out what other people are saying about the book by clicking on this link to search for this
hashtag on Twitter:
https://twitter.com/search?q=#tribehired
Contents

Chapter One . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter Two . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
M-V-C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Blades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Eloquent ORM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Artisan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Chapter Three . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Setting up environment on the local server . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Chapter Four . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Routes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

Chapter Five . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Blades . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Chapter Six . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Chapter Seven . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Chapter Eight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Schema Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Chapter Nine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Eloquent ORM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Chapter Ten . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Chapter Eleven . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Chapter Twelve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
CONTENTS

CRUD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Chapter Thirteen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Deploying live . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

Chapter Fourteen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Deploy DB live . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Chapter Fifteen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Further customizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Chapter One
Our goal is to build a to-do list application in a typical work environment. We will learn the concepts
that laravel uses, install the development environment, and deploy live.
Chapter 2 has a quick introduction to Model-View-Controller.
Chapter Two
Basic concepts

M-V-C.
Laravel uses Model View Controller to make programming pleasant.
Model.
This layer will handle retrieving data from a database and store it within a class.
View.
This consists of the html layer where your design of your site resides.
Controller.
All your logic to manipulate data resides here, and present it to the view.

Blades
Blade is a templating engine, that makes it easy to add dynamic data to html.

Eloquent ORM
It’s a simple way to work with the Database in the model layer.

Artisan
A command line interface for laravel. To create controllers, etc.
Chapter Three
Setting up environment on the local server
Step 1. Go to http://sourceforge.net/projects/laragon/, click download and execute
Step 2. Download php ide, http://www.sublimetext.com/3
Step 3: Set up a virtual host
Go to menu apache2 httpd.conf on laragon
Add this to the end of file.

1 <VirtualHost *:4000>
2 ServerName doesnotmatter
3 DocumentRoot "C:/lamp/www/myapp/public"
4 ServerAdmin bruno.skvorc@sitepoint.com
5 <Directory "C:/lamp/www/myapp/public">
6 Options Indexes FollowSymLinks
7 AllowOverride All
8 Require all granted
9 Order allow,deny
10 Allow from all
11 </Directory>
12 </VirtualHost>

Add this to the top of the file (line 8)

1 Listen 0.0.0.0:4000

Step 4. Open shell and run “composer self-update”


Step 5: Install laravel
On the console

1 cd www
2 composer create-project laravel/laravel myapp ~4.2.0 --prefer-dist
Chapter Three 4

Step 6. Restart apache, and run http://localhost:4000


Step 7: Install foundation css framework
Go to foundation.zurb.com, and download foundation 5 via download everything button. Upload
css, img and jsfolders to myapp public folder.
Step 8: Create main design template
Go to myapp app views Create folder layouts Create page main.blade.php
Go to myapp app views Create page boilerplate.blade.php
Add the following

1 @extends('layouts.main')
2 @section('content')
3 hello world
4 @stop

Step 9: Restart apache


Chapter Four
Routes
Let’s create initial routes for the to-do list.
Go to myapp app routes.php and enter the following:

1 Route::get('/', function()
2 {
3 return View::make('todos.index');
4 });
5
6 Route::get('/todos', function()
7 {
8 return View::make('todos.index');
9 });
10
11 Route::get('/todos/{id}', function($id)
12 {
13 return View::make('todos.show')->withId($id);
14 });

Go to views folder, and create todos folder, then create index.blade.php, enter the following:

1 hello world!
Chapter Five
Templates
Go to views layouts main.blade.php
Enter the following:

1 <!doctype html>
2 <html class="no-js" lang="en">
3 <head>
4 <meta charset="utf-8" />
5 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6 <title>Foundation | Welcome</title>
7 <link rel="stylesheet" href="{{ asset('css/foundation.css') }}" />
8 {{HTML:: script('js/vendor/modernizr.js')}}
9 </head>
10
11 <body>
12
13 <!-- Header and Nav -->
14
15 <nav class="top-bar" data-topbar>
16 <ul class="title-area">
17 <li class="name">
18 <h1><a href="#">ODOT</a></h1>
19 </li>
20 </ul>
21 </nav>
22
23 <!-- End Header and Nav -->
24
25 <div class="row">
26 <div class="large-12">
27 @yield('content')
28 </div>
29 </div>
30
31
Chapter Five 7

32 <!-- Footer -->


33
34 <footer class="row">
35 <div class="large-12 columns">
36 <hr />
37 <div class="row">
38 <div class="large-6 columns">
39 <p> © copyrighted</p>
40 </div>
41 </div>
42 </div>
43 </footer>
44
45 {{HTML:: script('js/vendor/jquery.js')}}
46 {{HTML:: script('js/foundation.min.js')}}
47 {{HTML:: script('js/app.js')}}
48 <script>
49 $(document).foundation();
50 </script>
51 </body>
52 </html>

Blades
Go to views todos index.blade.php

1 @extends('layouts.main')
2 @section('content')
3 <h2>All Todo lists</h2>
4
5 Hello world!
6
7 @stop
Chapter Six
Controllers
Step 1: Let’s create a controller to handle all the to do list actions
On the console,

1 cd workspace/myapp
2 php artisan route
3 php artisan controller:make TodoListController

View the page created on app controllers TodoListController.php


Step 2
Go to routes.php, and add the following:

1 Route::get('/', 'TodoListController@index');

Go to TodoListController.php, and update index function

1 echo "via controller";


2 return View::make('todos.index');

Preview this page: http://todos-183975.apse1.nitrousbox.com:4000/ It goes via controller


Preview this page: http://todos-183975.apse1.nitrousbox.com:4000/todos Routes loads the view di-
rectly
Update routes.php:

1 Route::get('/', 'TodoListController@index');
2 Route::get('/todos', 'TodoListController@index');

Update TodoListController.php
Chapter Six 9

1 Remove echo "via controller";


Chapter Seven
Database
1. Install postgres locally first
Download and install postgres from http://www.enterprisedb.com/products-services-training/pgdownload#window
2. System settings
Add the following to System Advanced system settings Advanced Environment Variables Path

1 C:\Program Files\PostgreSQL\9.4\bin

on httpd.conf,

1 LoadFile "C:\lamp\bin\php\php-5.6.3\libpq.dll"

On php.ini, uncomment,

1 extension=php_pdo_pgsql.dll
2 extension=php_pgsql.dll

Restart services
3. Create a database
On console,

1 psql -U postgres -h localhost


2 create database odot;

4: Connect your laravel app to pgsql


Get machine name from your console, example: action@todos-183975:∼$ or Windows->Search
Computer->Right click and select properties
Open bootstrap start.php, and update the following to line 29
Chapter Seven 11

1 from
2 'local' => array('homestead'),
3 to
4 'local' => array('todos-183975'),
5 (or 'local' => array('Laptop'),)

Update app config database.php

1 'default' => 'pgsql',

Update app config local database.php to odot

1 'mysql' => array(


2 'driver' => 'pgsql',
3 'host' => 'localhost',
4 'database' => 'odot',
5 'username' => 'postgres',
6 'password' => 'root',
7 'charset' => 'utf8',
8 'collation' => 'utf8_unicode_ci',
9 'prefix' => '',
10 )

Step 4: Check to see if we are connected to the database


Go to routes.php, and add the following

1 Route::get('/db', function(){
2 return DB::select('SELECT current_database();');
3 });

Run the following http://todos-183975.apse1.nitrousbox.com:4000/db


Chapter Eight
Schema Builder
The Laravel Schema class provides a database agnostic way of manipulating table
step 1: Let’s create a table via a schema builder
On console,

1 cd workspace/myapp
2 php artisan migrate:make create_todo_lists_table --create=todo_lists

Go to database migrations 2014_12_18_160918_create_todo_lists_table.php


On line 15,

1 Schema::create('todo_lists', function(Blueprint $table)


2 {
3 $table->increments('id');
4 $table->string('name')->unique();
5 $table->timestamps();
6 });

On console,

1 php artisan migrate


Chapter Nine
Eloquent ORM
Retrieve and display data via eloquent ORM
step 1: We create a model for the TodoList table

1 Create `TodoList.php` in folder `app` `model`


2
3 Add the following

1 <?PHP
2 Class TodoList Extends Eloquent {}

Step 2: Update Controller to massage data and pass to view to show all lists

1 Open `controllers` `TodoListController.php`


2 Update index function

1 $todo_lists = TodoList::all();
2 return View::make('todos.index')->with('todo_lists', $todo_lists);

Step 3: Update view to display data

1 Open `views` `todos` `index.blade.php`


2 Update the following below All todo lists header
Chapter Nine 14

1 <ul>
2 @foreach($todo_lists as $list)
3 <li>{{{ $list->name }}}</li>
4 @endforeach
5 </ul>

Step 4: Update Controller to get data for 1 list

1 Open `controllers` `TodoListController.php`


2 Update show function

1 $list = TodoList::findOrFail($id);
2 return View::make('todos.show')->withList($list);

Step 5: Update view to show 1 list

1 Create `views` `todos` `show.blade.php`


2 Add the following

1 <h2>{{{$list->name}}}</h2>

Step 6: Update routes.php


Remove the following

1 Route::get('/todos', 'TodoListController@index');
2
3 Route::get('/todos/{id}', function($id)
4 {
5 return View::make('todos.show')->withId($id);
6 });

Replace with

1 Route::resource('todos', 'TodoListController');

Now, run http://todos-183975.apse1.nitrousbox.com:4000/todos/1


Chapter Ten
Forms
We create an Add new form
Step 1: Update Controller to create a new list

1 Open `controllers` `TodoListController.php`


2 Update create function

1 $list = new TodoList();


2 $list->name = "Another List";
3 $list->save();
4 return "Create another list";

Now, run http://todos-183975.apse1.nitrousbox.com:4000/todos/create Now, run http://todos-183975.apse1.nitrousbo


Step 2: Update Controller

1 Open `controllers` `TodoListController.php`


2
3 Update create function

1 return View::make('todos.create');

Step 3: Create blade at views/todos/create.blade.php, and add the following


Chapter Ten 16

1 @extends('layouts.main')
2 @section('content')
3 {{ Form::open(array('route' => 'todos.store')) }}
4 {{Form::label('title', 'List title') }}
5 {{Form::text('title') }}
6 {{Form::submit('submit', array('class' => 'button')) }}
7 {{ Form::close() }}
8 @stop

Step 4: Update Controller


Open controllers TodoListController.php Update store function

1 public function store()


2 {
3 $name = Input::get('title');
4 $list = new TodoList();
5 $list->name = $name;
6 $list->save();
7 return Redirect::route('todos.index');
8 }
9
10 //for cross site injection via form
11 public function __construct()
12 {
13 $this->beforeFilter('csrf', array('on' => 'post'));
14 }
Chapter Eleven
Validation
1. We validate fields entered into form, only unique title entered
Step 1: Let’s update Controller

1 Open `controllers` `TodoListController.php`


2 Update store function

1 public function store()


2 {
3 //define rules
4 $rules = array(
5 'title' => array('required', 'unique:todo_lists,name')
6 );
7
8 //pass input to validator
9 $validator = Validator::make(Input::all(), $rules);
10
11 //test if input fails
12 if($validator->fails()){
13 return Redirect::route('todos.create');
14 }
15
16 $name = Input::get('title');
17 $list = new TodoList();
18 $list->name = $name;
19 $list->save();
20 return Redirect::route('todos.index');
21 }

2. Let’s give a good error message


Step 1: Update Controller
Chapter Eleven 18

1 Open `controllers` `TodoListController.php`


2 Update store function

1 //test if input fails


2 if($validator->fails()){
3 //$messages = $validator->messages();
4 return Redirect::route('todos.create')->withErrors($validator)->withInput();
5 }

Step 2: Go to create.blade.php, add the following

1 {{ $errors->first('title', '<small class="error">:message</small>') }}

1. Let’s give a good success message, if entered correctly


Open controllers TodoListController.php Update store function

1 return Redirect::route('todos.index')->withMessage('List was created');

1 Open `view` `layouts` `main.blade.php` add the following on line 25

1 @if (Session::has('message'))
2 <div class="alert-box success">
3 {{{ Session::get('message') }}}
4 </div>
5 @endif
Chapter Twelve
CRUD
1. Let update index page with links to show a task and create a task

1 Step 1: Open `app` `views` `todos` `index.blade.php`, and add the following

1 @foreach($todo_lists as $list)
2 <h4>{{ link_to_route('todos.show', $list->name, [$list->id]) }} </h4>
3 @endforeach

1 Step 2: Add the following

1 {{ link_to_route('todos.create', 'Create New List', null, ['class' => 'success b\


2 utton']) }}

2. Let’s show one task


Step 1: Open app views todos show.blade.php, and add the following

1 <div class="large-12 column">


2 <h1>{{{$list->name}}}</h1>
3 <p>{{link_to_route('todos.index', 'back')}}</p>
4 </div>

3. Let’s edit a task


Step 1: Open app views todos index.blade.php, and add the following
Chapter Twelve 20

1 @foreach($todo_lists as $list)
2 <h4>{{ link_to_route('todos.show', $list->name, [$list->id]) }} </h4>
3 <ul class="no-bullet button-group">
4 <li>
5 {{ link_to_route('todos.edit', 'edit', [$list->id], ['class' => 'tiny button']) \
6 }}
7 </li>
8 </ul>
9 @endforeach

Step 2: Open TodoListController.php, and update edit function

1 public function edit($id)


2 {
3 $list = TodoList::findOrFail($id);
4 return View::make('todos.edit')->withList($list);
5 }

Step 3: Create app views todos edit.blade.php, and add the following

1 @extends('layouts.main')
2 @section('content')
3 {{ Form::model($list, array('route' => 'todos.update', $list->id)) }}
4 {{Form::label('name', 'List title') }}
5 {{Form::text('name') }}
6 {{ $errors->first('title', '<small class="error">:message</small>') }}
7 {{Form::submit('submit', array('class' => 'button')) }}
8 {{ Form::close() }}
9 @stop

Step 4: Check right method to submit form. Open command prompt

1 ls workspace/myapp
2 php artisan routes

Step 5: Update app view todos edit.blade.php, and add the following

1 {{ Form::model($list, array('route' => ['todos.update', $list->id], 'method' => \


2 'PUT')) }}

Step 6: Update submitted form section, go to TodoListController.php, and change the update
function
Chapter Twelve 21

1 public function update($id)


2 {
3 //define rules
4 $rules = array(
5 'name' => array('required', 'unique:todo_lists,name')
6 );
7
8 //pass input to validator
9 $validator = Validator::make(Input::all(), $rules);
10
11 //test if input fails
12 if($validator->fails()){
13 //$messages = $validator->messages();
14 return Redirect::route('todos.edit', $id)->withErrors($validator)->withInput();
15 }
16
17 $name = Input::get('name');
18 $list = TodoList::findOrFail($id);
19 $list->name = $name;
20 $list->update();
21 return Redirect::route('todos.index')->withMessage('List was updated');
22 }

Step 7: Update construct for put method

1 public function __construct()


2 {
3 $this->beforeFilter('csrf', array('on' => ['post', 'put']));
4 }

4. Let’s delete a task

1 Step 1: Open `app` `views` `todos` `index.blade.php`, and add the following
Chapter Twelve 22

1 <li>
2 {{ Form::model($list, ['route' => ['todos.destroy', $list->id], 'method' => 'del\
3 ete']) }}
4 {{ Form::button('destroy', ['type'=>'submit', 'class'=>'tiny alert button']) }}
5 {{ Form::close() }}
6 </li>

Step 2: Open TodoListController.php, and update destroy function

1 public function destroy($id)


2 {
3 $todo_list = TodoList::findOrFail($id)->delete();
4 return Redirect::route('todos.index')->withMessage('Item deleted');
5 }

Step 3: Create javascript for confirm delete dialog, create public js app.js, and add the following:

1 $(document).ready(function(){
2
3 //confirm all destroys
4 $('form').submit(function(event) {
5 var method = $(this).children(':hidden[name=_method]').val();
6 if($.type(method) != 'undefined' && method == 'DELETE') {
7 if(!confirm('Are you sure?')){
8 event.preventDefault();
9 }
10 }
11 });
12 });

Step 4: Go to views layouts main.blade.php, and make sure this line exists

1 {{HTML:: script('js/app.js')}}
Chapter Thirteen
Deploying live
1. Sign up for a free heroku account on heroku.com
2. Install git for windows.

Go to http://windows.github.com/ and install. Also register an account on github.com.

1. Download the heroku toolbelt at https://toolbelt.heroku.com/ and run


2. Create Procfile document in www myapp vendor, add following

1 web: vendor/bin/heroku-php-apache2 public

1. Go to myapp .gitignore

Remove composer.lock from .gitignore

1. Run shell

1 composer update

1. Run command prompt


Chapter Thirteen 24

1 cd ../../
2 cd lamp/www/myapp
3
4 git init
5 git add .
6
7 $ git commit -m "Added a Procfile."
8 $ heroku login
9 heroku create another2 --buildpack https://github.com/heroku/heroku-buildpack-php
10 $heroku git:remote -a another2
11 git push heroku master

1. Run http://another2.herokuapp.com/public/
2. To update files in the future.

1 git status
2 git add .
3 $ git commit -m "Added a Procfile."
4 git push heroku master
Chapter Fourteen
Deploy DB live
1. Addon database

1 heroku addons:add heroku-postgresql:dev


2 heroku config

1. Configure laravel to use postgres for live

Open app config database.php

1 'default' => 'pgsql'


2
3 Set the following at the top of database.php
4
5 $url = parse_url(getenv("DATABASE_URL"));
6
7 $host = $url["host"];
8 $username = $url["user"];
9 $password = $url["pass"];
10 $database = substr($url["path"], 1);

Change pgsql entry to

1 'pgsql' => array(


2 'driver' => 'pgsql',
3 'host' => $host,
4 'database' => $database,
5 'username' => $username,
6 'password' => $password,
7 'charset' => 'utf8',
8 'prefix' => '',
9 'schema' => 'public',
10 ),

push and migrate, via shell


Chapter Fourteen 26

1 $ git add .
2 $ git commit -m "Convert to use Heroku PostgreSQL database"
3 $ git push heroku master

Run http://myapplive.herokuapp.com/public/db via browser

1 $ heroku run php /app/artisan migrate

Run http://myapplive.herokuapp.com/public via browser

1. Make site work on local and live

First echo db details, on database.php, add following

1 $url = parse_url(getenv("DATABASE_URL"));
2
3 $host = $url["host"];
4 $username = $url["user"];
5 $password = $url["pass"];
6 $database = substr($url["path"], 1);
7
8 echo "$host, $username, $password, $database <br>";

Now deploy, and copy details above echoed by http://myapplive.herokuapp.com/public/db


Now go back to database.php and update something like this

1 $host = "ec2-23-21-187-45.compute-1.amazonaws.com";
2 $username = "hkmwzesuiraeta";
3 $password = "XHvSrzTSABQU-F8ZD7SBrwSXcV";
4 $database = "ddtddkj86frea6";

Now, deploy again and run http://myapplive.herokuapp.com/public/db


If works, run http://myapplive.herokuapp.com/public
Congratulations your todolist is now live.
Chapter Fifteen
Further customizations
1. Re-factoring code for simplicity (refactor form)
Create views todos partials _form.blade.php, and add the following

1 {{Form::label('name', 'List title') }}


2 {{Form::text('name') }}
3 {{ $errors->first('name', '<small class="error">:message</small>') }}
4 {{Form::submit('submit', array('class' => 'button')) }}

Go to edit.blade.php, and update the following

1 @extends('layouts.main')
2 @section('content')
3 {{ Form::model($list, array('route' => ['todos.update', $list->id], 'method' => \
4 'PUT')) }}
5 @include('todos.partials._form')
6 {{ Form::close() }}
7 @stop

Go to create.blade.php and update the following

1 @extends('layouts.main')
2 @section('content')
3 {{ Form::open(array('route' => 'todos.store')) }}
4 @include('todos.partials._form')
5 {{ Form::close() }}
6 @stop

Open TodoListController.php, and go to store function


Chapter Fifteen 28

1 public function store()


2 {
3 //define rules
4 $rules = array(
5 'name' => array('required', 'unique:todo_lists')
6 );
7
8 //pass input to validator
9 $validator = Validator::make(Input::all(), $rules);
10
11 //test if input fails
12 if($validator->fails()){
13 //$messages = $validator->messages();
14 return Redirect::route('todos.create')->withErrors($validator)->withInput();
15 }
16
17 $name = Input::get('name');
18 $list = new TodoList();
19 $list->name = $name;
20 $list->save();
21 return Redirect::route('todos.index')->withMessage('List was created');
22 }

2. Create database relationship to items in a task


Open command prompt and run the the following

1 .cd workspace/myapp
2 .php artisan migrate:make create_todo_items_table --create=todo_items

Open the following document like this, database migrations daffadfdas_create_todo_items_-


table.php, and go to public function up

1 public function up()


2 {
3 Schema::create('todo_items', function(Blueprint $table)
4 {
5 $table->increments('id');
6 $table->integer('todo_list_id');
7 $table->string('content')->unique();
8 $table->dateTime('completed_on')->nullable();
9 $table->timestamps();
10 });
11 }
Chapter Fifteen 29

We create foreign key relationships via Eloquent.


Open models TodoList.php, and update the following

1 class TodoList extends Eloquent{} {


2
3 public function listItems()
4 {
5 return $this->hasMany('TodoItem');
6 }
7
8 }

Create models TodoItem.php and update the following

1 <?php
2
3 class TodoItem extends Eloquent {
4
5 public function todoList()
6 {
7 return $this->belongsTo('TodoList');
8 }
9
10 }

Now run instruction to create todo_items table

1 php artisan migrate

3. Retrieve items from a task list


(Add some rows into table via client)
Open TodoListController.php, and go to show function
Chapter Fifteen 30

1 public function show($id)


2 {
3 $list = TodoList::findOrFail($id);
4 $items = $list->listItems()->get();
5 return View::make('todos.show')->withList($list)->withItems($items);
6 }

Open show.blade.php, and update the following

1 @extends('layouts.main')
2 @section('content')
3 <div class="large-12 column">
4 <h1>{{{$list->name}}}</h1>
5 @foreach ($items as $item)
6 <h4>{{{$item->content}}}</h4>
7 @endforeach
8 <p>{{link_to_route('todos.index', 'back')}}</p>
9 </div>
10 @stop

4. How to troubleshoot sql issues for website


Open routes.php and add the following at the bottom

1 Event::listen('illuminate.query', function($query){
2 var_dump($query);
3 });

You might also like