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

TNRAO College of Information

Technology - Rajkot
M.Sc.IT & CA Semester - 1 (w.e.f. 2016)

Study Material
Of
CS-02 Advance Web Development in Laravel

Asifkhan Yusufzai
(HOD)
TNRAO College – Rajkot
TNRAO College of Information Technology - Rajkot 2

Unit – 1

Object Oriented Programming in PHP

The Basics:

Object Oriented Concepts


Before we go in detail, let‘s define important terms related to Object Oriented
Programming.

 Class − This is a programmer-defined data type, which includes local


functions as well as local data. You can think of a class as a template for
making many instances of the same kind (or class) of object.

 Object − An individual instance of the data structure defined by a class.


You define a class once and then make many objects that belong to it.
Objects are also known as instance.

 Member Variable − These are the variables defined inside a class. This
data will be invisible to the outside of the class and can be accessed via
member functions. These variables are called attribute of the object once an
object is created.

 Member function − These are the function defined inside a class and are
used to access object data.

 Inheritance − When a class is defined by inheriting existing function of a


parent class then it is called inheritance. Here child class will inherit all or
few member functions and variables of a parent class.

 Parent class − A class that is inherited from by another class. This is also
called a base class or super class.

 Child Class − A class that inherits from another class. This is also called a
subclass or derived class.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 3

 Polymorphism − This is an object oriented concept where same function


can be used for different purposes. For example function name will remain
same but it make take different number of arguments and can do different
task.

 Overloading − a type of polymorphism in which some or all of operators


have different implementations depending on the types of their arguments.
Similarly functions can also be overloaded with different implementation.

 Data Abstraction − Any representation of data in which the


implementation details are hidden (abstracted).

 Encapsulation − refers to a concept where we encapsulate all the data and


member functions together to form an object.

 Constructor − refers to a special type of function which will be called


automatically whenever there is an object formation from a class.

 Destructor − refers to a special type of function which will be called


automatically whenever an object is deleted or goes out of scope.

Defining PHP Classes


The general form for defining a new class in PHP is as follows −

<?php

class phpClass {

var $var1;

var $var2 = "constant string";

function myfunc ($arg1, $arg2) {

[..]

[..]

} ?>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 4

Here is the description of each line −

 The special form class followed by the name of the class that you want to
define.

 A set of braces enclosing any number of variable declarations and function


definitions.

 Variable declarations start with the special form var, which is followed by a
conventional $ variable name; they may also have an initial assignment to a
constant value.

 Function definitions look much like standalone PHP functions but are local to
the class and will be used to set and access object data.

Example
Here is an example which defines a class of Books type −

<?php
class Books {
/* Member variables */
var $price;
var $title;

/* Member functions */
function setPrice($par){
$this->price = $par;
}

function getPrice(){
echo $this->price ."<br/>";
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 5

function setTitle($par){
$this->title = $par;
}

function getTitle(){
echo $this->title ." <br/>";
}
}
?>

The variable $this is a special variable and it refers to the same object ie. itself.

Creating Objects in PHP:


Once you defined your class, then you can create as many objects as you
like of that class type. Following is an example of how to create object
using newoperator.

$physics = new Books;


$maths = new Books;
$chemistry = new Books;

Here we have created three objects and these objects are independent of each
other and they will have their existence separately. Next we will see how to
access member function and process member variables.

Calling Member Functions:


After creating your objects, you will be able to call member functions related to
that object. One member function will be able to process member variable of
related object only.

Following example shows how to set title and prices for the three books by calling
member functions.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 6

$physics->setTitle( "Physics for High School" );


$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );
$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

Now you call another member functions to get the values set by in above example −

$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();
$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −

Physics for High School


Advanced Chemistry
Algebra
10
15
7

Constructor Functions:
Constructor Functions are special type of functions which are called automatically
whenever an object is created. So we take full advantage of this behaviour, by
initializing many things through constructor functions.

PHP provides a special function called __construct() to define a constructor. You


can pass as many as arguments you like into the constructor function.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 7

Following example will create one constructor for Books class and it will initialize
price and title for the book at the time of object creation.

function __construct( $par1, $par2 ) {


$this->title = $par1;
$this->price = $par2;
}

Now we don't need to call set function separately to set price and title. We can
initialize these two member variables at the time of object creation only. Check
following example below −

$physics = new Books( "Physics for High School", 10 );


$maths = new Books ( "Advanced Chemistry", 15 );
$chemistry = new Books ("Algebra", 7 );

/* Get those set values */


$physics->getTitle();
$chemistry->getTitle();
$maths->getTitle();

$physics->getPrice();
$chemistry->getPrice();
$maths->getPrice();

This will produce the following result −

Physics for High School


Advanced Chemistry
Algebra
10
15
7

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 8

Destructor:
Like a constructor function you can define a destructor function using
function__destruct(). You can release all the resources with-in a destructor.

Inheritance:
PHP class definitions can optionally inherit from a parent class definition by using
the extends clause. The syntax is as follows −

class Child extends Parent {


<definition body>
}

The effect of inheritance is that the child class (or subclass or derived class) has
the following characteristics −

 Automatically has all the member variable declarations of the parent class.

 Automatically have all the same member functions as the parent, which (by
default) will work the same way as those functions do in the parent.

Following example inherits Books class and adds more functionality based on the
requirement.

class Novel extends Books {


var $publisher;
function setPublisher($par){
$this->publisher = $par;
}
function getPublisher(){
echo $this->publisher. "<br />";
}
}

Now apart from inherited functions, class Novel keeps two additional member
functions.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 9

Function Overriding:
Function definitions in child classes override definitions with the same name in
parent classes. In a child class, we can modify the definition of a function
inherited from parent class.

In the following example getPrice and getTitle functions are overridden to return
some values.

function getPrice() {
echo $this->price . "<br/>";
return $this->price;
}

function getTitle(){
echo $this->title . "<br/>";
return $this->title;
}

Public Members:
Unless you specify otherwise, properties and methods of a class are public. That
is to say, they may be accessed in three possible situations −

 From outside the class in which it is declared

 From within the class in which it is declared

 From within another class that implements the class in which it is declared

Till now we have seen all members as public members. If you wish to limit the
accessibility of the members of a class then you define class members as
private or protected.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 10

Private members:
By designating a member private, you limit its accessibility to the class in which it
is declared. The private member cannot be referred to from classes that inherit
the class in which it is declared and cannot be accessed from outside the class.

A class member can be made private by using private keyword infront of the
member.

class MyClass {
private $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}

private function myPrivateFunction() {


return("I'm not visible outside!");
}
}

When MyClass class is inherited by another class using extends,


myPublicFunction() will be visible, as will $driver. The extending class will not
have any awareness of or access to myPrivateFunction and $car, because they
are declared private.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 11

Protected members:
A protected property or method is accessible in the class in which it is declared,
as well as in classes that extend that class. Protected members are not available
outside of those two kinds of classes. A class member can be made protected by
using protected keyword in front of the member.

Here is different version of MyClass −

class MyClass {
protected $car = "skoda";
$driver = "SRK";

function __construct($par) {
// Statements here run every time
// an instance of the class
// is created.
}
function myPublicFunction() {
return("I'm visible!");
}

protected function myPrivateFunction() {


return("I'm visible in child class!");
}
}

Interfaces:
Interfaces are defined to provide a common function names to the implementers.
Different implementors can implement those interfaces according to their
requirements. You can say, interfaces are skeletons which are implemented by
developers.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 12

As of PHP5, it is possible to define an interface, like this −

interface Mail {
public function sendMail();
}

Then, if another class implemented that interface, like this −

class Report implements Mail {


// sendMail() Definition goes here
}

Constants:
A constant is somewhat like a variable, in that it holds a value, but is really more
like a function because a constant is immutable. Once you declare a constant, it
does not change.

Declaring one constant is easy, as is done in this version of MyClass −

class MyClass {

const requiredMargin = 1.7;

function __construct($incomingValue) {

// Statements here run every time an instance of the class is created.

In this class, requiredMargin is a constant. It is declared with the keyword const,


and under no circumstances can it be changed to anything other than 1.7. Note
that the constant's name does not have a leading $, as variable names do.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 13

Abstract Classes:
An abstract class is one that cannot be instantiated, only inherited. You declare
an abstract class with the keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the
parent's class declaration must be defined by the child; additionally, these
methods must be defined with the same visibility.

abstract class MyAbstractClass {


abstract function myAbstractFunction() {
}
}

Note that function definitions inside an abstract class must also be preceded by
the keyword abstract. It is not legal to have abstract function definitions inside a
non-abstract class.

Static Keyword:
Declaring class members or methods as static makes them accessible without
needing an instantiation of the class. A member declared as static can not be
accessed with an instantiated class object (though a static method can).

Try out following example −

<?php
class Foo {
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
?>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 14

Calling parent constructors:


Instead of writing an entirely new constructor for the subclass, let's write it by
calling the parent's constructor explicitly and then doing whatever is necessary in
addition for instantiation of the subclass. Here's a simple example −

class Name {
var $_firstName;
var $_lastName;

function Name($first_name, $last_name) {


$this->_firstName = $first_name;
$this->_lastName = $last_name;
}
function toString() {
return($this->_lastName .", " .$this->_firstName);
}
}
class NameSub1 extends Name {
var $_middleInitial;
function NameSub1($first_name, $middle_initial, $last_name) {
Name::Name($first_name, $last_name);
$this->_middleInitial = $middle_initial;
}
function toString() {
return(Name::toString() . " " . $this->_middleInitial);
}
}

In this example, we have a parent class (Name), which has a two-argument


constructor, and a subclass (NameSub1), which has a three-argument

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 15

constructor. The constructor of NameSub1 functions by calling its parent


constructor explicitly using the :: syntax (passing two of its arguments along) and
then setting an additional field. Similarly, NameSub1 defines its non constructor
toString() function in terms of the parent function that it overrides.

NOTE − A constructor can be defined with the same name as the name of a
class. It is defined in above example.

Scope Resolution Operator (::)

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler


terms, the double colon, is a token that allows access to static, constant, and
overridden properties or methods of a class.

When referencing these items from outside the class definition, use the name of
the class.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's
value can not be a keyword (e.g. self, parent and static).

Example #1 :: from outside the class definition

<?php
class MyClass {
const CONST_VALUE = 'A constant value';
}

$classname = 'MyClass';
echo $classname::CONST_VALUE; // As of PHP 5.3.0
echo MyClass::CONST_VALUE;
?>

Three special keywords self, parent and static are used to access properties or methods
from inside the class definition.

Example #2 :: from inside the class definition

<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';

public static function doubleColon() {

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 16

echo parent::CONST_VALUE . "\n";


echo self::$my_static . "\n";
}
}

$classname = 'OtherClass';
$classname::doubleColon(); // As of PHP 5.3.0

OtherClass::doubleColon();
?>

When an extending class overrides the parents definition of a method, PHP will not
call the parent's method. It's up to the extended class on whether or not the
parent's method is called. This also applies to Constructors and
Destructors, Overloading, and Magic method definitions.

Example #3 Calling a parent's method

<?php
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()\n";
}
}
class OtherClass extends MyClass
{
// Override parent's definition
public function myFunc()
{
// But still call the parent function
parent::myFunc();
echo "OtherClass::myFunc()\n";
}
}

$class = new OtherClass();


$class->myFunc();
?>

Abstract Classes:
PHP 5 introduces abstract classes and methods. Classes defined as abstract may
not be instantiated, and any class that contains at least one abstract method must
also be abstract. Methods defined as abstract simply declare the method's
signature - they cannot define the implementation.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 17

An abstract class is one that cannot be instantiated, only inherited. You declare
an abstract class with the keyword abstract, like this −

When inheriting from an abstract class, all methods marked abstract in the
parent's class declaration must be defined by the child; additionally, these
methods must be defined with the same visibility.

abstract class MyAbstractClass {


abstract function myAbstractFunction() {
}
}

Note that function definitions inside an abstract class must also be preceded by
the keyword abstract. It is not legal to have abstract function definitions inside a
non-abstract class.

<?php
// Example #1 Abstract class example

abstract class AbstractClass


{
// Our abstract method only needs to define the required arguments
abstract protected function prefixGender($gender,$name);
}

class GenderClass extends AbstractClass


{
// Our child class may define optional arguments not in the parent's signature
public function prefixGender($gender, $name, $separator = ".")
{
if ($gender == "Male") {
$prefix = "Mr";
} elseif ($gender == "Female") {
$prefix = "Mrs";
} else {
$prefix = "";
}
return "{$prefix}{$separator} {$name}";
}
}

$class = new GenderClass;


echo $class->prefixGender("Male","Asifkhan"), "<br>";
echo $class->prefixGender("Female","Manisha"), "<br>";
?>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 18

Interfaces:
Interfaces are defined to provide a common function names to the implementers.
Different implementors can implement those interfaces according to their
requirements. You can say, interfaces are skeletons which are implemented by
developers.

As of PHP5, it is possible to define an interface, like this −

interface Mail {
public function sendMail();
}

Then, if another class implemented that interface, like this −

class Report implements Mail {


// sendMail() Definition goes here
}

Anonymous classes:

Anonymous Class is simply a class definition without a name. It is defined just like
any other class. In truth, they do have internally generated names so we do not
need to provide the names

<?php
class namedClass {
protected $className;
protected $classProp = 'I am a student property';
public function __construct($value) {
$this->className = $value;
}
public function returnProperty( $propName ) {
if( !empty( $this->$propName ) ) {
return $this->$propName;
} else {
return 'property not found';
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 19

}
}
$object = new namedClass( 'Student' );
echo $object -> returnProperty( 'className' ) . "<br>"; // Named
echo $object -> returnProperty( 'classProp' ); // I am a class property
?>

Object Iteration:

PHP 5 provides a way for objects to be defined so it is possible to iterate through a


list of items, with, for example a foreach statement. By default,
all visible properties will be used for the iteration.

As the output shows, the foreach iterated through all of the visible properties
that could be accessed.

Why use iterators?

The advantage of the Iterator is that it provides a high-level abstracted interface,


so the code that calls it does not need to worry so much about what is going on.

At the same time it allows you to process large data sources (fetching rows from a
db, reading lines from a file) in chunks without having to load everything into
memory at once.

<?php
class MyClass
{
public $Name = 'Asifkhan';
public $Age = '49';
public $City = 'Rajkot';

protected $protected = 'protected var';


private $private = 'private var';

function iterateVisible() {
foreach ($this as $key => $value) {
echo "$key => $value <br>";
}
}
}

$class = new MyClass();

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 20

foreach($class as $key => $value) {


echo "$key => $value <br>";
}
echo "<br>";
$class->iterateVisible();
?>

Magic Methods in PHP:


Magic methods in php are some predefined function by php compiler which
executes on some event. Magic methods start with prefix __, for example __call, __get,
__set. In PHP. __construct is a magic method which automatically calls on creating object
of the classes. There are verous magic methods in php. Here we will discuss some of the
most comman magic methods of php which will be use in object oriented programming.
First of let us review all magic method with short description.

List of List of Magic Methods in PHP


Magic Method Description

This magic methods is called when someone create object of your class.
__construct Usually this is used for creating constructor in php5.

This magic method is called when object of your class is unset. This is
__destruct
just opposite of __construct.

This method called when your object attempt to read property or


__get
variable of the class which is inaccessible or unavailable.

This method called when object of your class attempts to set value of
__set
the property which is really inaccessible or unavailable in your class.

This magic methods trigger when isset() function is applied on any


__isset
property of the class which isinaccessible or unavailable.

__unset is something opposite of isset method. This method triggers


__unset when unset() function called on inaccessible or unavailable property of
the class.

__call magic method trigger when you are attempting to call method or
__call
function of the class which is either inaccessible or unavailable.

__callstatic execture when inaccessible or unavailable method is in static


__callstatic
context.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 21

__sleep methods trigger when you are going to serialize your class
__sleep
object.

__wakeup __wakeup executes when you are un serializing any class object.

__toString __toString executes when you are using echo on your object.

__invoke __invoke called when you are using object of your class as function

Above list is the most conman used magic methods in php object oriented programming.
Above magic methods of php executes on some specific events occur on your class
object. For example if you simply echo your object then __toString method triggers. Let
us create group of related magic method and analyze how it is working.

__construct and __destruct magic method in PHP


__construct method trigger on creation of object. And __destruct triggers of deletion of
object. Following is very basic example of __construct and __destruct magic method in
php:

class test
{
function __construct()
{

echo 1;
}

function __destruct()
{

echo 2;
}

$objT = new test(); //__construct get automatically executed and print 1 on screen

unset($objT); //__destruct triggers and print 2.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 22

Final Keyword:
PHP 5 introduces the final keyword, which prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is being defined
final then it cannot be extended.

Following example results in Fatal error: Cannot override final method


BaseClass::moreTesting()

<?php
class BaseClass {
public function test() {
echo "BaseClass::test() called<br>";
}

final public function moreTesting() {


echo "BaseClass::moreTesting() called<br>";
}
}

class ChildClass extends BaseClass {


public function moreTesting() {
echo "ChildClass::moreTesting() called<br>";
}
}
?>

Object Cloning:

Creating a copy of an object with fully replicated properties is not always the
wanted behavior. A good example of the need for copy constructors is if you have
an object which represents a GTK window and the object holds the resource of this
GTK window, when you create a duplicate you might want to create a new window
with the same properties and have the new object hold the resource of the new
window. Another example is if your object holds a reference to another object
which it uses and when you replicate the parent object you want to create a new
instance of this other object so that the replica has its own separate copy.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 23

An object copy is created by using the clone keyword (which calls the
object's __clone() method if possible). An object's __clone() method cannot be
called directly.

$copy_of_object = clone $object;

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's
properties. Any properties that are references to other variables will remain
references.

void __clone ( void )

Once the cloning is complete, if a __clone() method is defined, then the newly
created object's __clone() method will be called, to allow any necessary
properties that need to be changed.

Example #1 Cloning an object

<?php
// Example of Copy Object with reference

echo "Copy with Reference Object Example" . "<br>";

class Customer {
private $name;

public function setName($name) {


$this->name = $name;
}

public function getName() {


return $this->name;
}
}

$c1 = new Customer();


$c1->setName("Sunil");

$c2 = $c1; //only reference or memory assigned to $c2

echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 24

$c2->setName("Vishal");
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";

// Cloning Object using __clone() method

echo "Cloning Object Example" . "<br>";


class CustomerClone {
private $name;

public function setName($name) {


$this->name = $name;
}

public function getName() {


return $this->name;
}

public function __clone() {


$c = new Customer();
$c->setName($this->name);
return $c;
}

$c1 = new CustomerClone();


$c1->setName("Sunil");

$c2 = clone $c1; //new object $c2 created

echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";

$c2->setName("Vishal");
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";

?>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 25

Comparing Objects:

When using the comparison operator (==), object variables are compared in a
simple manner, namely: Two object instances are equal if they have the same
attributes and values (values are compared with ==), and are instances of the
same class.

When using the identity operator (===), object variables are identical if and only
if they refer to the same instance of the same class.

An example will clarify these rules.

Example #1 Example of object comparison in PHP 5

<?php
function bool2str($bool)
{
if ($bool == false) {
return 'FALSE';
} else {
return 'TRUE';
}
}

function compareObjects(&$o1, &$o2)


{
echo 'First Object == Second Object : ' . bool2str($o1 == $o2) . "<br>";
}

class Class1
{
public $flag;

function Class1($flag = true) {


$this->flag = $flag;
}
}
class Class2
{
public $flag;

function Class2($flag = true) {


$this->flag = $flag;
}
}

$obj1_Class1 = new Class1();

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 26

$obj2_Class1 = new Class1();

$obj3_Class2 = new Class2();


$objRef_Class1 = $obj1_Class1;

echo "<br> Two instances of the same class <br>";


compareObjects($obj1_Class1, $obj2_Class1);

echo "<br> Two references to the same instance <br>";


compareObjects($obj1_Class1, $objRef_Class1);

echo "<br> Instances of two different classes <br>";


compareObjects($obj1_Class1, $obj3_Class2);
?>

Type hinting:

With Type hinting we can specify the expected data type (arrays, objects,
interface, etc.) for an argument in a function declaration. This practice can be
most advantageous because it results in better code organization and improved
error messages.

How to do array type hinting?

When we would like to force a function to get only arguments of the type array,
we can put the keyword array in front of the argument name, with the following
syntax:

function functionName (array $argumentName)


{
//code
}

Does PHP support type hinting to basic data types?

It depends.
Whereas PHP5 doesn‘t allow type hinting for basic data types (integers, floats,
strings and booleans), PHP7 does supportscalar type hinting.
PHP5 does not support type hinting to basic data types like integers, booleans
or strings. So, when we need to validate that an argument belongs to a basic data
type, we can use one of PHP‘s ―is_‖ family functions. For example:
• is_bool - to find out whether a variable is a boolean (true or false).
• is_int - to find out whether a variable is an integer.
• is_float - to find out whether a variable is a float (3.14, 1.2e3 or 3E-10).
• is_null - to find out whether a variable

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 27

<?php

// The function can only get array as an argument.

function calcNumMilesOnFullTank(array $models)


{
foreach($models as $item)
{
echo $carModel = $item[0];
echo " : ";
echo $numberOfMiles = $item[1] * $item[2];
echo "<br />";
}
}

// This statement give error because Array as argument required


calcNumMilesOnFullTank("Toyota");

$models = array(
array('Toyota', 12, 44),
array('BMW', 13, 41)
);

// This will work because correct argument Array is passed


calcNumMilesOnFullTank($models);

?>

Late Static Binding in PHP:

What is Binding?
In simple software language, ―connecting a method call, to the method body is known as
binding‖.

Types of Binding
There are two types of binding:

1. Static binding (early binding)


2. Dynamic binding (late binding)

Example of Static Binding in PHP


Here in this case, class association is made during compile time.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 28

<?php
class Vehicle {
public function color() {
echo 'car color is RED';
}
}
$vehicle = new Vehicle();
$vehicle->color();
?>
This would print the output as: car color is RED

Example of Dynamic Binding in PHP


Here in this case, class association is not made until the object is created at
execution time.

<?php
class Vehicle {
public function color() {
echo 'car color is RED';
}
}

class Honda extends Vehicle {


public function color() {
echo 'car color is BLUE';
}
}

$vehicle = new Honda();


$vehicle->color();
?>

This would print the output as: car color is BLUE

But, have you heard of another binding called ―Late Static Binding‖!! No…. then
let‘s go through that :) with some interesting example.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 29

What is Late Static Binding?


PHP 5.3 implemented a new feature called Late Static Binding, which is used to reference
the called class regarding the static method inheritance.
Why the Name Late Static Binding?
It is the combination of two concepts, i.e., Late Binding and Static Binding.
Late binding comes from the fact that static:: keyword will not be resolved using the class
where the method is defined, but it will rather be computed using runtime information.
Static binding comes from the fact that it can be used for (but is not limited to) static
method calls.

Why It Came Into the Picture?

To overcome the use of self keyword, Late static binding concept came. self does
not follow the rules of inheritance and it always resolves to the class in which it is
used. For example – if you make a method in a parent class and call it from a child
class, self will always reference the parent, instead of child.

But in case of Late Static Binding, static keyword has been used extensively to
represent the class where it is first used, i.e., it binds to the runtime class.

Example of Late Static Binding in PHP with Self, Parent and Static

<?php
class GrandFather {
function classname(){
return __CLASS__;
}

function selfname(){
return self::classname();
}
function staticname(){
return static::classname();
}
}

class Father extends GrandFather {


function parentname(){
return parent::classname();
}

function classname(){
return __CLASS__;
}
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 30

class Son extends Father {


function parentname(){
return parent::classname();
}
function classname(){
return __CLASS__;
}
}
// Son object is created
$son = new Son();

echo $son->selfname() . '<br/>';


echo $son->parentname() . '<br/>';
echo $son->staticname();
?>

Objects and references:

One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by
references by default". This is not completely true. This section rectifies that general
thought using some examples.

A PHP reference is an alias, which allows two different variables to write to the same
value. As of PHP 5, an object variable doesn't contain the object itself as value anymore.
It only contains an object identifier which allows object accessors to find the actual object.
When an object is sent by argument, returned or assigned to another variable, the
different variables are not aliases: they hold a copy of the identifier, which points to the
same object.

Example #1 References and Objects

<?php
class A {
public $foo = 1;
}

$a = new A;
$b = $a; // $a and $b are copies of the same identifier // ($a) = ($b) = <id>
$b->foo = 2;

echo $a->foo."\n";

$c = new A;
$d = &$c; // $c and $d are references // ($c,$d) = <id>

$d->foo = 2;
echo $c->foo."\n";
$e = new A;

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 31

function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>

The above example will output:


2
2
2

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 32

Unit – 1

Bootstrap Basics

Introduction:
What is Twitter Bootstrap?
Bootstrap is a sleek, intuitive, and powerful, mobile first front-end framework for faster
and easier web development. It uses HTML, CSS, and Javascript.

History
Bootstrap was developed by Mark Otto and Jacob Thornton at Twitter. It was released as
an open source product in August 2011 on GitHub.

Why Use Bootstrap?

 Mobile first approach: Bootstrap 3 framework consists of Mobile first styles


throughout the entire library instead of them in separate files.

 Browser Support: It is supported by all popular browsers.

 Easy to get started: With just the knowledge of HTML and CSS anyone can get
started with Bootstrap. Also the Bootstrap official site has a good documentation.

 Responsive design: Bootstrap's responsive CSS adjusts to Desktops, Tablets and


Mobiles.

 Provides a clean and uniform solution for building an interface for developers.

 It contains beautiful and functional built-in components which are easy to


customize.

 It also provides web-based customization.

 And best of all it is an open source.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 33

What Bootstrap Package Includes?

 Scaffolding: Bootstrap provides a basic structure with Grid System, link styles,
and background. This is covered in detail in the section Bootstrap Basic
Structure.

 CSS: Bootstrap comes with the feature of global CSS settings, fundamental HTML
elements styled and enhanced with extensible classes, and an advanced grid
system. This is covered in detail in the section Bootstrap with CSS.

 Components: Bootstrap contains over a dozen reusable components built to


provide iconography, dropdowns, navigation, alerts, pop-overs, and much more.
This is covered in detail in the section Layout Components.

 JavaScript Plugins: Bootstrap contains over a dozen custom jQuery plugins. You
can easily include them all, or one by one. This is covered in details in the section
Bootstrap Plugins.

 Customize: You can customize Bootstrap's components, LESS variables, and


jQuery plugins to get your very own version.

Download Bootstrap

You can download the latest version of Bootstrap from http://getbootstrap.com/. When
you click on this link, you will get to see a screen as below:
Here you can see two buttons:

 Download Bootstrap: Clicking this, you can download the precompiled and minified
versions of Bootstrap CSS, JavaScript, and fonts. No documentation or original
source code files are included.

 Download Source: Clicking this, you can get the latest Bootstrap LESS and
JavaScript source code directly from GitHub.

If you work with Bootstrap's uncompiled source code, you need to compile the LESS files
to produce usable CSS files. For compiling LESS files into CSS, Bootstrap officially
supports only Recess, which is Twitter's CSS hinter based on less.js.

For better understanding and ease of use, we shall use precompiled version of Bootstrap
throughout the tutorial. As the files are complied and minified, you don't have to bother
every time including separate files for individual functionality.

File structure:
Precompiled Bootstrap
Once the compiled version Bootstrap is downloaded, extract the ZIP file, and you will see
the following file/directory structure:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 34

As you can see, there are compiled CSS and JS (bootstrap.*), as well as compiled
and minified CSS and JS (bootstrap.min.*). Fonts from Glyphicons are included, as
it is the optional Bootstrap theme.

Bootstrap Source Code


If you have downloaded the Bootstrap source code then the file structure would be
as follows:

The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS,
and icon fonts (respectively).

 The dist/ folder includes everything listed in the precompiled download


section above.

 docs-assets/, examples/, and all *.html files are Bootstrap documentation.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 35

HTML Template:

A basic HTML template using Bootstrap would look like this:

<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- Bootstrap -->


<link href="css/bootstrap.min.css" rel="stylesheet">

<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>

<body>
<h1>Hello, world!</h1>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->


<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->

<script src="js/bootstrap.min.js"></script>
</body>
</html>

Here you can see the jquery.js, bootstrap.min.js and bootstrap.min.css files
that are included to make a normal HTML file to the Bootstrapped Template. Just
make sure to include jQuery library before you include Bootstrap library.

Example
Now let's try an example using the above template. Try the following example
using Try it option available at the top right corner of the below sample code box
on our website:

<h1>Hello, world!</h1>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 36

What is a Grid?

In graphic design, a grid is a structure (usually two-dimensional) made up of a


series of intersecting straight (vertical, horizontal) lines used to structure the
content. It is widely used to design layout and content structure in print design. In
web design, it is a very effective method to create a consistent layout rapidly and
effectively using HTML and CSS.

To put in simple words, grids in web design organise and structure content, makes
the websites easy to scan and reduces the cognitive load on users.

What is Bootstrap Grid System?

Bootstrap's grid system allows up to 12 columns across the page.

If you do not want to use all 12 column individually, you can group the columns
together to create wider columns:

Bootstrap's grid system is responsive, and the columns will re-arrange depending on the
screen size: On a big screen it might look better with the content organized in three
columns, but on a small screen it would be better if the content items were stacked on top
of each other.

Bootstrap includes a responsive, mobile first fluid grid system that appropriately
scales up to 12 columns as the device or viewport size increases. It includes
predefined classes for easy layout options, as well as powerful mixins for
generating more semantic layouts.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 37

Let us understand the above statement. Bootstrap 3 is mobile first in the sense
that the code for Bootstrap now starts by targeting smaller screens like mobile
devices, tablets, and then ―expands‖ components and grids for larger screens such
as laptops, desktops.

Mobile First Strategy


 Content
o Determine what is most important.

 Layout
o Design to smaller widths first.

o Base CSS address mobile device first; media queries address for
tablet, desktops.

 Progressive Enhancement
o Add elements as screen size increases.

Working of Bootstrap Grid System

Grid systems are used for creating page layouts through a series of rows and
columns that house your content. Here's how the Bootstrap grid system works:

 Rows must be placed within a .container class for proper alignment and
padding.

 Use rows to create horizontal groups of columns.

 Content should be placed within the columns, and only columns may be the
immediate children of rows.

 Predefined grid classes like .row and .col-xs-4 are available for quickly
making grid layouts. LESS mixins can also be used for more semantic
layouts.

 Columns create gutters (gaps between column content) via padding. That
padding is offset in rows for the first and the last column via negative
margin on .rows.

 Grid columns are created by specifying the number of twelve available


columns you wish to span. For example, three equal columns would use
three .col-xs-4.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 38

Grid Options

The following table summarizes aspects of how Bootstrap grid system works
across multiple devices:

Extra small Small Medium Large devices


devices devices devices Desktops
Phones Tablets Desktops (≥1200px)
(<768px) (≥768px) (≥992px)
Grid behavior Horizontal at Collapsed to Collapsed to Collapsed to
all times start, start, horizontal start, horizontal
horizontal above above
above breakpoints breakpoints
breakpoints
Max container None (auto) 750px 970px 1170px
width
Class prefix .col-xs- .col-sm- .col-md- .col-lg-
# of columns 12 12 12 12
Max column Auto 60px 78px 95px
width
Gutter width 30px (15px 30px (15px 30px (15px on 30px (15px on
on each side on each side each side of a each side of a
of a column) of a column) column) column)
Nestable Yes Yes Yes Yes
Offsets Yes Yes Yes Yes
Column Yes Yes Yes Yes
ordering

Basic Grid Structure


Following is basic structure of Bootstrap grid:
<div class="container">
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">...</div>
</div>
<div class="container">....

Example: Mobile, tablet, desktops

We have seen an example for Medium and Large Device. Now let us take it
to another level, where we would want to change it for the extra small phone size
as well. Say we want to add the option for the columns to be split 75%/25% for
tablets, we go like this:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 39

<div class="col-sm-3 col-md-6 col-lg-4">....</div>


<div class="col-sm-9 col-md-6 col-lg-8">....</div>

Now this gives us 3 different column layouts at each point. On a phone, it will be 75% on
the left, and 25% on the right. On a tablet, it will be 50%/50% again, and on a large
viewport, it will be 33%/66%. Three different layouts for each of the three responsive
sizes. Check it out in the following example. (Here styling for each column is used. You
can avoid it.)

Responsive Column Resets:

With the four tiers of grids available, you are bound to run into issues where at
certain breakpoints, the columns don't clear quite right as one is taller than the other. To
fix that, use a combination of a class .clearfix and the responsive utility classes as shown
in the following example:

<div class="container">
<div class="row" >

<div class="col-xs-6 col-sm-3" style="background-color: #dedef8;


box-shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>

<div class="col-xs-6 col-sm-3" style="background-color: #dedef8;box-shadow:


inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut.
</p>
</div>

<div class="clearfix visible-xs"></div>

<div class="col-xs-6 col-sm-3" style="background-color: #dedef8;


box-shadow:inset 1px -1px 1px #444, inset -1px 1px 1px #444;">

<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco


laboris nisi ut aliquip ex ea commodo consequat.
</p>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 40

</div>
<div class="col-xs-6 col-sm-3" style="background-color: #dedef8;box-shadow:
inset 1px -1px 1px #444, inset -1px 1px 1px #444;">

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do


eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim
</p>
</div>
</div>
</div>

Resize your viewport or check it out on your phone for a desired result of this
example.

Offset Columns:

Offsets are a useful feature for more specialized layouts. They can be used
to push columns over for more spacing (for example). The .col-xs=* classes don‘t
support offsets, but they are easily replicated by using an empty cell.

To use offsets on large displays, use the .col-md-offset-* classes. These classes
increase the left margin of a column by * columns where * range from 1 to 11.

In the following example, we have <div class="col-md-6">..</div>. We will


center this using class .col-md-offset-3.

<div class="container">
<h1>Hello, world!</h1>
<div class="row" >
<div class="col-xs-6 col-md-offset-3" style="background-color: #dedef8;box-
shadow: inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>
</div>
</div>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 41

Nesting Columns:

To nest your content with the default grid, add a new .row and set of .col-md-*
columns within an existing .col-md-* column. Nested rows should include a set of
columns that add up to 12.

In the following example, the layout has two columns, with the second one being
split into four boxes over two rows.

<div class="container">
<h1>Hello, world!</h1>
<div class="row">

<div class="col-md-3" style="background-color: #dedef8;box-shadow: inset 1px -


1px 1px #444, inset -1px 1px 1px #444;">
<h4>First Column</h4>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>

<div class="col-md-9" style="background-color: #dedef8;box-shadow: inset 1px -


1px 1px #444, inset -1px 1px 1px #444;">
<h4>Second Column- Split into 4 boxes</h4>

<div class="row">
<div class="col-md-6" style="background-color: #B18904; box-shadow: inset 1px
-1px 1px #444, inset -1px 1px 1px 444;">
<p>Consectetur art party Tonx culpa semiotics. Pinterest assumenda minim
organic quis.
</p>
</div>

<div class="col-md-6" style="background-color: #B18904; box-shadow: inset 1px


-1px 1px #444, inset -1px 1px 1px 444;">
<p> sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim
ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.
</p>
</div>
</div>
<div class="row">
<div class="col-md-6" style="background-color: #B18904; box-shadow: inset 1px
-1px 1px #444, inset -1px 1px 1px 444;">
<p>quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 42

</p>
</div>
<div class="col-md-6" style="background-color: #B18904; box-shadow: inset 1px
-1px 1px #444, inset -1px 1px 1px #444;">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim.</p>
</div>
</div>
</div>
</div>
</div>

Fluid Grid System:

In Bootstrap (version 3.2+), you can use the class .container-fluid to create
the fluid layouts in order to utilize the 100% width of the viewport.

The class .container-fluid simply applies the horizontal margin with the
value auto and left and right padding of 15px on element to offset the left and
right margin of -15px(i.e. margin: 0 -15px;) used on the .row.

The following code creates a fluid layout that covers 100% width of the screen.

<div class="container-fluid">

<div class="row">
<div class="col-*-*"> First </div>
</div>
<div class="row">
<div class="col-*-*"> Second </div>
<div class="col-*-*">Third </div>
<div class="col-*-*"> Forth</div>
</div>
<div class="row">
Fifth
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 43

Responsive Web design

Responsive Web Design the approach that suggests that design and
development should respond to the user‘s behavior and environment based on
screen size, platform and orientation. The practice consists of a mix of flexible
grids and layouts, images and an intelligent use of CSS media queries. As the user
switches from their laptop to iPad, the website should automatically switch to
accommodate for resolution, image size and scripting abilities. In other words, the
website should have the technology to automatically respond to the user‘s
preferences. This would eliminate the need for a different design and development
phase for each new gadget on the market

Responsive Web design is not only about adjustable screen resolutions and
automatically resizable images, but rather about a whole new way of thinking
about design. Let‘s talk about all of these features, plus additional ideas in the
making.

 Adjusting Screen Resolution


 Flexible Images
 Custom Layout Structure
 Showing or Hiding Content

The point is: with responsive design, the website automatically adjusts based on the
device the viewer sees it in.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 44

Implementation of Bootstrap tags:

Typography:

Bootstrap uses Helvetica Neue, Helvetica, Arial, and sans-serif in its default font
stack. Using typography feature of Bootstrap you can create headings,
paragraphs, lists and other inline elements. Let see learn each one of these in the
following sections.

Example -1:

<div class="container-fluid">
<p align="center"> Example of Heading tag of HTML </p>
<h1>h1 Bootstrap heading (36px)</h1>
<h2>h2 Bootstrap heading (30px)</h2>
<h3>h3 Bootstrap heading (24px)</h3>
<h4>h4 Bootstrap heading (18px)</h4>
<h5>h5 Bootstrap heading (14px)</h5>
<h6>h6 Bootstrap heading (12px)</h6>
</div>

Example -2:

<div class="container-fluid">
<p align="center"> Example of Heading tag with <small> </p>
<h1>Lighter, Secondary Text</h1>
<p>The small element is used to create a lighter, secondary text in any
heading:</p>
<h1>h1 heading <small>secondary text</small></h1>
<h2>h2 heading <small>secondary text</small></h2>
<h3>h3 heading <small>secondary text</small></h3>
<h4>h4 heading <small>secondary text</small></h4>
<h5>h5 heading <small>secondary text</small></h5>
<h6>h6 heading <small>secondary text</small></h6>
</div>

Example -3:

<div class="container-fluid">

<h1> < mark > </h1>


<h1>Highlight Text</h1>
<p>Use the mark element to <mark>highlight</mark> text.</p>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 45

<h1> < abbr > </h1>


<h1>Abbreviations</h1>
<p>The abbr element is used to mark up an abbreviation or acronym:</p>
<p>The <abbr title="World Health Organization">WHO</abbr> was founded in
1948.</p>

<h1> < blockquote > </h1>


<h1>Blockquotes</h1>
<p>The blockquote element is used to present content from another
source:</p>
<blockquote>
<p>For 50 years, WWF has been protecting the future of nature. The world's
leading conservation organization, WWF works in 100 countries and is supported
by 1.2 million members in the United States and close to 5 million globally.</p>
<footer>From WWF's website</footer>
</blockquote>

<h1> < dl > </h1>


<h1>Description Lists</h1>
<p>The dl element indicates a description list:</p>
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

<h1> < code > </h1>


<h1>Code Snippets</h1>
<p>Inline snippets of code should be embedded in the code element:</p>
<p>The following HTML elements: <code>span</code>,
<code>section</code>, and <code>div</code> defines a section in a
document.</p>

<h1> < kbd > </h1>


<h1>Keyboard Inputs</h1>
<p>To indicate input that is typically entered via the keyboard, use the kbd
element:</p>
<p>Use <kbd>ctrl + p</kbd> to open the Print dialog box.</p>
<hr>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 46

<h1> < pre > </h1>


<h1>Multiple Code Lines</h1>
<p>For multiple lines of code, use the pre element:</p>
<pre>
Text in a pre element
is displayed in a fixed-width
font, and it preserves
both spaces and
line breaks.
</pre>

<h2>Contextual Colors</h2>
<p>Use the contextual classes to provide "meaning through colors":</p>
<p class="text-muted">This text is muted.</p>
<p class="text-primary">This text is important.</p>
<p class="text-success">This text indicates success.</p>
<p class="text-info">This text represents some information.</p>
<p class="text-warning">This text represents a warning.</p>
<p class="text-danger">This text represents danger.</p>

<h2>Contextual Backgrounds</h2>
<p>Use the contextual background classes to provide "meaning through
colors":</p>
<p class="bg-primary">This text is important.</p>
<p class="bg-success">This text indicates success.</p>
<p class="bg-info">This text represents some information.</p>
<p class="bg-warning">This text represents a warning.</p>
<p class="bg-danger">This text represents danger.</p>

<div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 47

Bootstrap Basic Table


A basic Bootstrap table has a light padding and only horizontal dividers.
The .table class adds basic styling to a table:

Striped Rows
The .table-striped class adds zebra-stripes to a table:

Bordered Table
The .table-bordered class adds borders on all sides of the table and cells:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 48

Hover Rows
The .table-hover class adds a hover effect (grey background color) on table rows:

Condensed Table
The .table-condensed class makes a table more compact by cutting cell padding in half:

Contextual Classes
Contextual classes can be used to color table rows (<tr>) or table cells (<td>):

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 49

The contextual classes that can be used are:

Responsive Tables
The .table-responsive class creates a responsive table. The table will then scroll horizontally on
small devices (under 768px). When viewing on anything larger than 768px wide, there is no
difference:

Bootstrap Forms:

Form controls automatically receive some global styling with Bootstrap:

All textual <input>, <textarea>, and <select> elements with class .form-control have a width
of 100%

Bootstrap Form Layouts


Bootstrap provides three types of form layouts:

 Vertical form (this is default)


 Horizontal form
 Inline form

Standard rules for all three form layouts:

 Wrap labels and form controls in <div class="form-group"> (needed for optimum
spacing)
 Add class .form-control to all textual <input>, <textarea>, and <select> elements

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 50

<form>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

<form class="form-inline">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd">
</div>
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 51

A horizontal form stands apart from the other forms both in the amount of markup, and in the
presentation of the form.
Additional rules for a horizontal form:

 Add class .form-horizontal to the <form> element


 Add class .control-label to all <label> elements

<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" placeholder="Enter email">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="pwd">Password:</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="pwd" placeholder="Enter
password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label><input type="checkbox"> Remember me</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 52

Bootstrap Buttons
Button Styles
Bootstrap provides seven styles of buttons:

Default Primary Success Info Warning Danger Link


To achieve the button styles above, Bootstrap has the following classes:

 .btn-default
 .btn-primary
 .btn-success
 .btn-info
 .btn-warning
 .btn-danger
 .btn-link

The following example shows the code for the different button styles:
<button type="button" class="btn btn-default">Default</button>
<button type="button" class="btn btn-primary">Primary</button>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-info">Info</button>
<button type="button" class="btn btn-warning">Warning</button>
<button type="button" class="btn btn-danger">Danger</button>
<button type="button" class="btn btn-link">Link</button>

Button Sizes
Bootstrap provides four button sizes:

The classes that define the different sizes are:

 .btn-lg
 .btn-md
 .btn-sm
 .btn-xs

The following example shows the code for different button sizes:
<button type="button" class="btn btn-primary btn-lg">Large</button>
<button type="button" class="btn btn-primary btn-md">Medium</button>
<button type="button" class="btn btn-primary btn-sm">Small</button>
<button type="button" class="btn btn-primary btn-xs">XSmall</button>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 53

Block Level Buttons


A block level button spans the entire width of the parent element.

Add class .btn-block to create a block level button:

<button type="button" class="btn btn-primary btn-block">Button 1</button>

Active/Disabled Buttons
A button can be set to an active (appear pressed) or a disabled (unclickable) state:
Active Primary

The class .active makes a button appear pressed, and the class .disabled makes a button
unclickable:

<button type="button" class="btn btn-primary active">Active Primary</button>


<button type="button" class="btn btn-primary disabled">Disabled Primary</button>

Bootstrap Image Shapes

Rounded Corners
The .img-rounded class adds rounded corners to an image (IE8 does not support rounded
corners):
<img src="image1.jpg" class="img-rounded" alt="Image" width="304" height="236">

Circle
The .img-circle class shapes the image to a circle (IE8 does not support rounded corners):
<img src="image2.jpg" class="img-circle" alt="image" width="304" height="236">

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 54

Thumbnail
The .img-thumbnail class shapes the image to a thumbnail:
<img src="image3.jpg" class="img-thumbnail" alt="image" width="304" height="236">

Responsive Images
Images come in all sizes. So do screens. Responsive images automatically adjust to fit the size of
the screen.
Create responsive images by adding an .img-responsive class to the <img> tag. The image will
then scale nicely to the parent element.
The .img-responsive class applies display: block; and max-width: 100%; and height:
auto; to the image:
<img class="img-responsive" src="image4.jpg" alt="Image">

Glyphicons
Bootstrap provides 260 glyphicons from the Glyphicons Halflings set.

Glyphicons can be used in text, buttons, toolbars, navigation, forms, etc.

Here are some examples of glyphicons:

Glyphicon Syntax
A glyphicon is inserted with the following syntax:
<span class="glyphicon glyphicon-name"></span>

The name part in the syntax above must be replaced with the proper name of the glyphicon.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 55

Glyphicon Example
The following example shows different ways to use glyphicons:
<p>Envelope icon: <span class="glyphicon glyphicon-envelope"></span></p>
<p>Envelope icon as a link:
<a href="#"><span class="glyphicon glyphicon-envelope"></span></a>
</p>
<p>Search icon: <span class="glyphicon glyphicon-search"></span></p>
<p>Search icon on a button:
<button type="button" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</p>
<p>Search icon on a styled button:
<button type="button" class="btn btn-info">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</p>
<p>Print icon: <span class="glyphicon glyphicon-print"></span></p>
<p>Print icon on a styled link button:
<a href="#" class="btn btn-success btn-lg">
<span class="glyphicon glyphicon-print"></span> Print
</a>
</p>

Bootstrap Dropdowns

Basic Dropdown
A dropdown menu is a toggleable menu that allows the user to choose one value from a predefined
list:

<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-
toggle="dropdown">Dropdown Example
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 56

Example Explained
The .dropdown class indicates a dropdown menu.

To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and
the data-toggle="dropdown" attribute.

The .caret class creates a caret arrow icon (), which indicates that the button is a dropdown.

Add the .dropdown-menu class to a <ul> element to actually build the dropdown menu.

Dropdown Divider
The .divider class is used to separate links inside the dropdown menu with a thin horizontal
border:

<li class="divider"></li>

Dropdown Header
Dropdown Header Example

The .dropdown-header class is used to add headers inside the dropdown menu:

<li class="dropdown-header">Dropdown header 1</li>

Disable and Active items


Dropdown Disabled Example
Highlight a specific dropdown item with the .active class (adds a blue background color).

To disable an item in the dropdown menu, use the .disabled class (gets a light-grey text color
and a "no-parking-sign" icon on hover):

<li class="disabled"><a href="#">CSS</a></li>


<li class="active"><a href="#">HTML</a></li>

Dropdown Position
Dropdown Right Example
To right-align the dropdown, add the .dropdown-menu-right class to the element with .dropdown-
menu:

<ul class="dropdown-menu dropdown-menu-right">

Dropup
If you want the dropdown menu to expand upwards instead of downwards, change the <div>
element with class="dropdown" to "dropup":

<div class="dropup">

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 57

Dropdown Accessibility
To help improve accessibility for people using screen readers, you should include the
following role and aria-*attributes, when creating a dropdown menu:

<div class="dropdown">
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-
toggle="dropdown">Tutorials
<span class="caret"></span></button>
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">
<li role="presentation"><a role="menuitem" href="#">HTML</a></li>
<li role="presentation"><a role="menuitem" href="#">CSS</a></li>
<li role="presentation"><a role="menuitem" href="#">JavaScript</a></li>
<li role="presentation" class="divider"></li>
<li role="presentation"><a role="menuitem" href="#">About Us</a></li>
</ul>
</div>

Bootstrap Button Groups

Bootstrap allows you to group a series of buttons together (on a single line) in a button group:
AppleSamsungSony

Use a <div> element with class .btn-group to create a button group:

<div class="btn-group">
<button type="button" class="btn btn-primary">Apple</button>
<button type="button" class="btn btn-primary">Samsung</button>
<button type="button" class="btn btn-primary">Sony</button>
</div>

Tip: Instead of applying button sizes to every button in a group, use class .btn-group-
lg|sm|xs to size all buttons in the group:

<div class="btn-group btn-group-lg">


<button type="button" class="btn btn-primary">Apple</button>
<button type="button" class="btn btn-primary">Samsung</button>
<button type="button" class="btn btn-primary">Sony</button>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 58

Vertical Button Groups


Bootstrap also supports vertical button groups:

Use the class .btn-group-vertical to create a vertical button group:

<div class="btn-group-vertical">
<button type="button" class="btn btn-primary">Apple</button>
<button type="button" class="btn btn-primary">Samsung</button>
<button type="button" class="btn btn-primary">Sony</button>
</div>

Justified Button Groups


To span the entire width of the screen, use the .btn-group-justified class:

<div class="btn-group btn-group-justified">


<a href="#" class="btn btn-primary">Apple</a>
<a href="#" class="btn btn-primary">Samsung</a>
<a href="#" class="btn btn-primary">Sony</a>
</div>

Note: For <button> elements, you must wrap each button in a .btn-group class:

<div class="btn-group btn-group-justified">


<div class="btn-group">
<button type="button" class="btn btn-primary">Apple</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-primary">Samsung</button>
</div>
<div class="btn-group">
<button type="button" class="btn btn-primary">Sony</button>
</div>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 59

Bootstrap Navigation Bar


Navigation Bars
A navigation bar is a navigation header that is placed at the top of the page:

With Bootstrap, a navigation bar can extend or collapse, depending on the screen size.

A standard navigation bar is created with <nav class="navbar navbar-default">.

The following example shows how to add a navigation bar to the top of the page:
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

Inverted Navigation Bar


If you don't like the style of the default navigation bar, Bootstrap provides an alternative, black
navbar:

Just change the .navbar-default class into .navbar-inverse:

<nav class="navbar navbar-inverse">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 60

Navigation Bar With Dropdown

Navigation bars can also hold dropdown menus.

The following example adds a dropdown menu for the "Page 1" button:

<nav class="navbar navbar-inverse">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Page 1-1</a></li>
<li><a href="#">Page 1-2</a></li>
<li><a href="#">Page 1-3</a></li>
</ul>
</li>
<li><a href="#">Page 2</a></li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
</nav>

Navbar Forms

To add form elements inside the navbar, add the .navbar-form class to a form element and add an
input(s). Note that we have added a .form-group class to the div container holding the input. This
adds proper padding if you have more than one inputs (you will learn more about this in the Forms
chapter).

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 61

<nav class="navbar navbar-inverse">


<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
</ul>
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</nav>

Breadcrumbs
Another form for pagination, is breadcrumbs:

The .breadcrumb class indicates the current page's location within a navigational hierarchy:

<ul class="breadcrumb">
<li><a href="#">Home</a></li>
<li><a href="#">Private</a></li>
<li><a href="#">Pictures</a></li>
<li class="active">Vacation</li>
</ul>

Bootstrap Pagination
Basic Pagination
If you have a website with lots of pages, you may wish to add some sort of pagination to each
page. A basic pagination in Bootstrap looks like this:

To create a basic pagination, add the .pagination class to an <ul> element:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 62

<ul class="pagination">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ul>

Active State
The active state shows what is the current page:

Add class .active to let the user know which page he/she is on:

<ul class="pagination">
<li><a href="#">1</a></li>
<li class="active"><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
</ul>

Bootstrap Badges and Labels


Badges
Badges are numerical indicators of how many items are associated with a link:

The numbers (5, 10, and 2) are the badges.

Use the .badge class within <span> elements to create badges:

<a href="#">News <span class="badge">5</span></a><br>


<a href="#">Comments <span class="badge">10</span></a><br>
<a href="#">Updates <span class="badge">2</span></a>
Badges can also be used inside other elements, such as buttons:

The following example shows how to add badges to buttons:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 63

<button type="button" class="btn btn-


primary">Primary <span class="badge">7</span></button>

Labels
Labels are used to provide additional information about something:

Use the .label class, followed by one of the six contextual classes .label-default, .label-
primary, .label-success, .label-info, .label-warning or .label-danger, within
a <span> element to create a label:

<h1>Example <span class="label label-default">New</span></h1>


<h2>Example <span class="label label-default">New</span></h2>
<h3>Example <span class="label label-default">New</span></h3>
<h4>Example <span class="label label-default">New</span></h4>
<h5>Example <span class="label label-default">New</span></h5>
<h6>Example <span class="label label-default">New</span></h6>

Bootstrap Alerts
Alerts
Bootstrap provides an easy way to create predefined alert messages:

Alerts are created with the .alert class, followed by one of the four contextual classes .alert-
success, .alert-info, .alert-warning or .alert-danger:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 64

<div class="alert alert-success">


<strong>Success!</strong> Indicates a successful or positive action.
</div>

<div class="alert alert-info">


<strong>Info!</strong> Indicates a neutral informative change or action.
</div>

<div class="alert alert-warning">


<strong>Warning!</strong> Indicates a warning that might need attention.
</div>

<div class="alert alert-danger">


<strong>Danger!</strong> Indicates a dangerous or potentially negative action.
</div>

Closing Alerts

To close the alert message, add a .alert-dismissible class to the alert container. Then
add class="close" and data-dismiss="alert" to a link or a button element (when you click on
this the alert box will disappear).

<div class="alert alert-success alert-dismissible">


<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>
<strong>Success!</strong> Indicates a successful or positive action.
</div>

Bootstrap Progress Bars


Basic Progress Bar
A progress bar can be used to show a user how far along he/she is in a process.
Bootstrap provides several types of progress bars.
A default progress bar in Bootstrap looks like this:

To create a default progress bar, add a .progress class to a <div> element:

<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:70%">
<span class="sr-only">70% Complete</span>
</div>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 65

Progress Bar With Label


A progress bar with a label looks like this:

Remove the .sr-only class from the progress bar to show a visible percentage:

<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="70"
aria-valuemin="0" aria-valuemax="100" style="width:70%">
70%
</div>
</div>

Animated Progress Bar


Here is an "animated" progress bar:

Add class .active to animate the progress bar:

<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width:40%">
40%
</div>
</div>

Stacked Progress Bars


Progress bars can also be stacked:

Create a stacked progress bar by placing multiple bars into the same <div class="progress">:

<div class="progress">
<div class="progress-bar progress-bar success" role="progressbar" style="width:40%">
Free Space
</div>
<div class="progress-bar progress-bar-warning" role="progressbar" style="width:10%">
Warning
</div>
<div class="progress-bar progress-bar-danger" role="progressbar" style="width:20%">
Danger
</div>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 66

Bootstrap Wells
Wells
The .well class adds a rounded border around an element with a gray background color and some
padding:

<div class="well">Basic Well</div>

Well Size

Change the size of the well by adding the .well-sm class for small wells or .well-lg class for
large wells:

<div class="well well-sm">Small Well</div>


<div class="well well-lg">Large Well</div>

Bootstrap Carousel Plugins


The Carousel plugin is a component for cycling through elements, like a carousel (slideshow).

Tip: Plugins can be included individually (using Bootstrap's individual "carousel.js" file), or all at
once (using "bootstrap.js" or "bootstrap.min.js").

Carousel Example

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 67

Note: Carousels are not supported properly in Internet Explorer 9 and earlier (because they use
CSS3 transitions and animations to achieve the slide effect).

How To Create a Carousel


The following example shows how to create a basic carousel:
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
</ol>

<!-- Wrapper for slides -->


<div class="carousel-inner" role="listbox">
<div class="item active">
<img src="img_chania.jpg" alt="Chania">
</div>
<div class="item">
<img src="img_chania2.jpg" alt="Chania">
</div>
<div class="item">
<img src="img_flower.jpg" alt="Flower">
</div>

<div class="item">
<img src="img_flower2.jpg" alt="Flower">
</div>
</div>

<!-- Left and right controls -->


<a class="left carousel-control" href="#myCarousel" role="button" data-
slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#myCarousel" role="button" data-
slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 68

Example Explained
The outermost <div>:

Carousels require the use of an id (in this case id="myCarousel") for carousel controls to function
properly.

The class="carousel" specifies that this <div> contains a carousel.

The .slide class adds a CSS transition and animation effect, which makes the items slide when
showing a new item. Omit this class if you do not want this effect.

The data-ride="carousel" attribute tells Bootstrap to begin animating the carousel immediately
when the page loads.

The "Indicators" part:

The indicators are the little dots at the bottom of each slide (which indicates how many slides there
is in the carousel, and which slide the user are currently viewing).

The indicators are specified in an ordered list with class .carousel-indicators.

The data-target attribute points to the id of the carousel.

The data-slide-to attribute specifies which slide to go to, when clicking on the specific dot.

The "Wrapper for slides" part:

The slides are specified in a <div> with class .carousel-inner.

The content of each slide is defined in a <div> with class .item. This can be text or images.

The .active class needs to be added to one of the slides. Otherwise, the carousel will not be
visible.

The "Left and right controls" part:

This code adds "left" and "right" buttons that allows the user to go back and forth between the
slides manually.

The data-slide attribute accepts the keywords "prev" or "next", which alters the slide position
relative to its current position.

Bootstrap Jumbotron and Page Header

Creating a Jumbotron
A jumbotron indicates a big box for calling extra attention to some special content or information.
A jumbotron is displayed as a grey box with rounded corners. It also enlarges the font sizes of the
text inside it.
Tip: Inside a jumbotron you can put nearly any valid HTML, including other Bootstrap
elements/classes.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 69

Use a <div> element with class .jumbotron to create a jumbotron:

Jumbotron inside Container


Place the jumbotron inside the <div class="container"> if you want the jumbotron to NOT
extend to the edge of the screen:
<div class="container">
<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for developing
responsive, mobile-first projects on the web.</p>
</div>
<p>This is some text.</p>
<p>This is another text.</p>
</div>

Jumbotron outside Container


Place the jumbotron outside the <div class="container"> if you want the jumbotron to extend
to the screen edges:
<div class="jumbotron">
<h1>Bootstrap Tutorial</h1>
<p>Bootstrap is the most popular HTML, CSS, and JS framework for developing
responsive,
mobile-first projects on the web.</p>
</div>
<div class="container">
<p>This is some text.</p>
<p>This is another text.</p>
</div>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 70

Unit – 2

Introduction to Laravel

What is Laravel:

Laravel is an MVC framework with bundles, migrations, and Artisan CLI. Laravel
offers a robust set of tools and an application architecture that incorporates many
of the best features of frameworks like CodeIgniter, Yii, ASP.NET MVC, Ruby on
Rails, Sinatra, and others.
Laravel is an Open Source framework. It has a very rich set of features which will
boost the speed of Web Development. If you familiar with Core PHP and Advanced
PHP, Laravel will make your task easier. It will save a lot time if you are planning
to develop a website from scratch. Not only that, the website built in Laravel is
also secure. It prevents the various attacks that can take place on websites.

Features of Laravel:

Laravel offers the following key features:


 Modularity
 Testability
 Routing
 Configuration management
 Query builder and ORM (Object Relational Mapper)
 Schema builder, migrations, and seeding
 Template engine
 E-mailing
 Authentication
 Redis
 Queues
 Event and command bus

Laravel Installer:

Before installing Laravel, ensure that you have the following programs already
installed 1. Web server 2. PHP 3. MySQL 4. Composer 5. Integrated Development
Environment (IDE)

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 71

Web Server, PHP & MySQL


use XAMPP. XAMPP comes with Apache, MySQL and PHP. The good news is XAMPP
is cross platform.

How to install Laravel using composer


This section assumes you have already installed composer. In this section, we will;

1. browse to htdocs in XAMPP or where path to the web server where you want
to create
2. create a new Laravel project using composer
3. test new Laravel project creation in web browser

Step 1: browse to web server root

1. Assuming you installed XAMPP to C:/xampp/, open C:/xampp/htdocs using


windows explorer
2. Right click anywhere in C:/xampp/htdocs and select use composer here as
shown in the image below

Select use composer here. You will get the following command prompt window

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 72

Step 2: Create new Laravel project using composer

1. run the following command


2. composer create-project laravel/laravel larashop

You will get the following output in the command prompt

Wait for the installation to complete

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 73

Step 3: Test installation

Browser to the following URL in your web browser.

http://localhost/larashop/public/

If you do not get the above welcome page, use the comments section below to
share what you get and we will help you out with whatever challenges you will
face.

Database configuration
The database configuration file is located in /config/database.php. By default,
MySQL will be used as the database engine. You can set it to a different database
management system if you want but for this tutorial, we will leave the default
value.

We will update the following keys;

 database
 username
 password

Locate the following lines

'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 74

Update the above code to the following

'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'larashop'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', 'melody'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],

HERE,

 'database' => env('DB_DATABASE', 'larashop'), sets the database name to


larashop. You can go ahead and create an empty database larashop in
MySQL.
 'username' => env('DB_USERNAME', 'root'), sets root as the database
username that will be used for authentication. You should use a valid
username for your MySQL instance.
 'password' => env('DB_PASSWORD', 'melody'), sets melody as the
password that will be used to login. You should use a valid password for your
MySQL instance.

MVC Architecture:
MVC Architecture is rapidly became the industry‘s standard practice used in
every modern development environment. Many frameworks such as Ruby on Rails,
ASP.NET, CakePHP and CodeIgniter make use of it to separate the logic behind the
application from the representation layer.

An MVC architecture pattern let the web application have many different views
of a single common model. That is, in our current context of building an
eCommerce web applica-tion, a Category page, for example, can have multiple
views such as the Product List View or Product Gallery View. In an MVC
development environment, one model for the Category table will be created and
via that one model multiple views can be created

The MVC architecture pattern let the developer write a code that can be divided on
the basis of the following three things:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 75

• Model

A Model is the mode by which the developer can manipulate the data. It
consists of a layer residing between the data and the application. The data itself
can be stored in various types of database systems such as MySQL or even simple
XML or Excel files.

• Views

Views are the visual representation of our web application (presentation


layer), they are responsible for presenting the data that the Controller received
from the Model (business logic). They can be easily built using the Blade template
language or simply using plain PHP code. Blade is driven by template inheritance
and sections.

• Control

The primary function of a Controller is to handle requests and pass data


from the Model to the Views. Thus a Controller can be considered as the link
between our Model and Views.

The developer has the option to write her/his business logic either in Routers
or Controllers.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 76

Root Directory
The root directory of Laravel contains various folders and files as shown in the
following figure.

 app: This directory contains the core code of the application.

 bootstrap: This directory contains the application bootstrapping script.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 77

 config: This directory contains configuration files of application.

 database: This folder contains your database migration and seeds.

 public: This is the application‘s document root. It starts the Laravel


application. It also contains the assets of the application like JavaScript,
CSS, Images, etc.

 resources: This directory contains raw assets such as the LESS & Sass files,
localization and language files, and Templates that are rendered as HTML.

 storage: This directory contains App storage, like file uploads etc.
Framework storage (cache), and application-generated logs.

 test: This directory contains various test cases.

 vendor: This directory contains composer dependencies.

App Directory

This is the application directory. It contains a variety of additional directories,


which are described below:

 Console: All the artisan commands are stored in this directory.

 Events: This directory stores events that your application can raise. Events
may be used to alert other parts of your application that a given action has
occurred, providing a great deal of flexibility and decoupling.

 Exceptions: This directory contains your application's exception handler and


is also a good place to stick any exceptions thrown by your application.

 Http: This directory contains your controllers, filters, and requests.

 Jobs: This directory contains the queueable jobs for your application.

 Listeners: This directory contains the handler classes for your events.
Handlers receive an event and perform logic in response to the event being
fired. For example, a UserRegistered event might be handled by a
SendWelcomeEmail listener.

 Policies: This directory contains various policies of the application.

 Providers: This directory contains various service providers.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 78

Unit – 2

Installation

Via Laravel Installer


First, download the Laravel installer using Composer.

composer global require "laravel/installer=~1.1"

Make sure to place the ~/.composer/vendor/bin directory in your PATH so


the laravel executable is found when you run the laravel command in your terminal.

Once installed, the simple laravel new command will create a fresh Laravel installation in
the directory you specify. For instance, laravel new blog would create a directory
named blogcontaining a fresh Laravel installation with all dependencies installed. This
method of installation is much faster than installing via Composer.

Via Composer Create-Project


You may also install Laravel by issuing the Composer create-project command in your
terminal:

composer create-project laravel/laravel {directory} 4.2 --prefer-dist

Via Download
Once Composer is installed, download the 4.2 version of the Laravel framework and
extract its contents into a directory on your server. Next, in the root of your Laravel
application, run the php composer.phar install (or composer install) command to
install all of the framework's dependencies. This process requires Git to be installed on the
server to successfully complete the installation.

If you want to update the Laravel framework, you may issue the php composer.phar
updatecommand.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 79

Server Requirements

The Laravel framework has a few system requirements:

 PHP >= 5.4


 MCrypt PHP Extension

As of PHP 5.5, some OS distributions may require you to manually install the PHP
JSON extension. When using Ubuntu, this can be done via apt-get install php5-
json.

Permissions

Laravel may require one set of permissions to be configured: folders


within app/storage require write access by the web server.

Paths

Several of the framework directory paths are configurable. To change the location of these
directories, check out the bootstrap/paths.php file.

Unit – 2

Configuration

Introduction
All of the configuration files for the Laravel framework are stored in
the app/config directory. Each option in every file is documented, so feel free to look
through the files and get familiar with the options available to you.

Sometimes you may need to access configuration values at run-time. You may do so
using the Config class:

Accessing A Configuration Value

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

You may also specify a default value to return if the configuration option does not exist:

$timezone = Config::get('app.timezone', 'UTC');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 80

Setting A Configuration Value


Notice that "dot" style syntax may be used to access values in the various files. You may
also set configuration values at run-time:

Config::set('database.default', 'sqlite');

Configuration values that are set at run-time are only set for the current request,

and will not be carried over to subsequent requests.

Environment Configuration

Laravel provides facility to run your application in different environment like


testing, production etc. You can configure the environment of your application in
the .env file of the root directory of your application. If you have installed Laravel
using composer, this file will automatically be created.
In case you haven‘t installed Laravel, you can simply rename the .env.example file to
.env file. A sample of Laravel.env file is shown below.

You may also pass arguments to the environment method to check if the environment
matches a given value:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 81

if (App::environment('local'))
{
// The environment is local
}
if (App::environment('local', 'staging'))
{
// The environment is either local OR staging...
}

Protecting Sensitive Configuration

For "real" applications, it is advisable to keep all of your sensitive configuration out of your
configuration files. Things such as database passwords, Stripe API keys, and encryption
keys should be kept out of your configuration files whenever possible. So, where should
we place them? Thankfully, Laravel provides a very simple solution to protecting these
types of configuration items using "dot" files.

First, configure your application to recognize your machine as being in


the local environment. Next, create a .env.local.php file within the root of your project,
which is usually the same directory that contains your composer.json file.
The .env.local.php should return an array of key-value pairs, much like a typical Laravel
configuration file:

<?php
return array(
'TEST_STRIPE_KEY' => 'super-secret-sauce',
);

All of the key-value pairs returned by this file will automatically be available via
the $_ENV and $_SERVER PHP "superglobals". You may now reference these globals from
within your configuration files:

'key' => $_ENV['TEST_STRIPE_KEY']

Be sure to add the .env.local.php file to your .gitignore file. This will allow other
developers on your team to create their own local environment configuration, as well as
hide your sensitive configuration items from source control.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 82

Now, on your production server, create a .env.php file in your project root that contains
the corresponding values for your production environment. Like the .env.local.php file,
the production .env.php file should never be included in source control.

Note: You may create a file for each environment supported by your application. For
example, the development environment will load the .env.development.php file if it
exists. However, the production environment always uses the .env.php file.

Maintenance Mode
When your application is in maintenance mode, a custom view will be displayed for all
routes into your application. This makes it easy to "disable" your application while it is
updating or when you are performing maintenance. A call to the App::down method is
already present in your app/start/global.php file. The response from this method will be
sent to users when your application is in maintenance mode.

To enable maintenance mode, simply execute the down Artisan command:

php artisan down

To disable maintenance mode, use the up command:

php artisan up

To show a custom view when your application is in maintenance mode, you may add
something like the following to your application's app/start/global.php file:

App::down(function()

return Response::view('maintenance', array(), 503);

});

If the Closure passed to the down method returns NULL, maintenance mode will be
ignored for that request.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 83

Maintenance Mode & Queues

While your application is in maintenance mode, no queue jobs will be handled.


The jobs will continue to be handled as normal once the application is out of maintenance
mode.

Database Configuration
The database of your application can be configured from config/database.php file.
You can set configuration parameters that can be used by different databases and
you can also set the default one to use.

Laravel makes interacting with databases extremely simple across a variety of database backends
using either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel
supports four databases:

 MySQL
 Postgres
 SQLite
 SQL Server

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 84

Configuration
The database configuration for your application is located at config/database.php. In this
file you may define all of your database connections, as well as specify which connection
should be used by default. Examples for most of the supported database systems are
provided in this file.

By default, Laravel's sample environment configuration is ready to use with Laravel


Homestead, which is a convenient virtual machine for doing Laravel development on
your local machine. Of course, you are free to modify this configuration as needed for
your local database.

SQLite Configuration

After creating a new SQLite database using a command such as touch


database/database.sqlite, you can easily configure your environment variables to point
to this newly created database by using the database's absolute path:

DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite

SQL Server Configuration

Laravel supports SQL Server out of the box; however, you will need to add the connection
configuration for the database to your config/database.php configuration file:
'sqlsrv' => [
'driver' => 'sqlsrv',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
],

Naming the Application

The App Directory, by default, is namespaced under App. To rename it, you can
execute the following command and rename the namespace.
php artisan app:name <name-of-your-application>

Replace the <name-of-your-application> with the new name of your application


that you want to give.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 85

Unit – 3

Artisan

Introduction

Artisan is the command-line interface included with Laravel. It provides a number


of helpful commands that can assist you while you build your application. To view
a list of all available Artisan commands, you may use the list command:

php artisan list

Every command also includes a "help" screen which displays and describes the
command's available arguments and options. To view a help screen, simply
precede the name of the command with help:

php artisan help migrate

Writing Commands

In addition to the commands provided with Artisan, you may also build your own
custom commands. Commands are typically stored in
the app/Console/Commands directory; however, you are free to choose your own
storage location as long as your commands can be loaded by Composer.

Generating Commands

To create a new command, use the make:command Artisan command. This


command will create a new command class in
the app/Console/Commands directory. Don't worry if this directory does not exist
in your application, since it will be created the first time you run
the make:command Artisan command. The generated command will include the
default set of properties and methods that are present on all commands:

php artisan make:command SendEmails

Next, you will need to register the command before it can be executed via the
Artisan CLI.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 86

Command Structure

After generating your command, you should fill in


the signature and description properties of the class, which will be used when
displaying your command on the list screen. The handle method will be called
when your command is executed. You may place your command logic in this
method.

Database Creation and Migration:

To create the database for our Laravel project, we simply open the phpMyadmin
panel in our browser of choice and we proceed to create the database by giving it
a name and editing the security credentials.

Before getting started, we need to be sure to configure the database connection in


app/config/database.php file by editing the lines of PHP code containing the
credentials to match our database‘s credentials. Laravel‘s default database, which
is MySQL will be kept as our database management system for our current
project.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 87

After configuring the database we can start our application without the need for
firing up our XAMPP local server as Laravel utilizes the built-in development server
that is bundled with PHP version 5.4 or newer. To start our development server,
we simply use the Arti-san command

php artisan serve

Generating Migrations

Migrations are like version control for your database, allowing your team to easily
modify and share the application's database schema. Migrations are typically
paired with Laravel's schema builder to easily build your application's database
schema. If you have ever had to tell a teammate to manually add a column to
their local database schema, you've faced the problem that database migrations
solve.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 88

The Laravel Schema facade provides database agnostic support for creating and
manipulating tables across all of Laravel's supported database systems.

To create a migration, use the make:migration

Artisan command:

php artisan make:migration create_users_table

The new migration will be placed in your database/migrations directory. Each


migration file name contains a timestamp which allows Laravel to determine the
order of the migrations.

The --table and --create options may also be used to indicate the name of the
table and whether the migration will be creating a new table. These options simply
pre-fill the generated migration stub file with the specified table:

php artisan make:migration create_users_table --create=users

php artisan make:migration add_votes_to_users_table --table=users

If you would like to specify a custom output path for the generated migration, you
may use the --path option when executing the make:migration command. The
given path should be relative to your application's base path.

Migration Structure

A migration class contains two methods: up and down. The up method is used to
add new tables, columns, or indexes to your database, while the down method
should simply reverse the operations performed by the up method.

Within both of these methods you may use the Laravel schema builder to
expressively create and modify tables. To learn about all of the methods available
on the Schema builder, check out its documentation. For example, this
migration example creates a flights table:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 89

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateFlightsTable extends Migration


{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('airline');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('flights');
}
}

Running Migrations

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 90

Rolling Back Migrations

To rollback the latest migration operation, you may use the rollback command.
This command rolls back the last "batch" of migrations, which may include
multiple migration files:

php artisan migrate:rollback

You may rollback a limited number of migrations by providing the step option to
the rollbackcommand. For example, the following command will rollback the last
five migrations:

php artisan migrate:rollback --step=5

The migrate:reset command will roll back all of your application's migrations:

php artisan migrate:reset

Tables

Creating Tables

To create a new database table, use the create method on the Schema facade.
The create method accepts two arguments. The first is the name of the table,
while the second is a Closure which receives a Blueprint object that may be used
to define the new table:

Schema::create('users', function (Blueprint $table) {


$table->increments('id');
});

Of course, when creating the table, you may use any of the schema
builder's column methods to define the table's columns.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 91

Checking For Table / Column Existence

You may easily check for the existence of a table or column using
the hasTable and hasColumnmethods:

if (Schema::hasTable('users')) {
//
}

if (Schema::hasColumn('users', 'email')) {
//
}

Renaming / Dropping Tables


To rename an existing database table, use the rename method:

Schema::rename($from, $to);

To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop('users');

Schema::dropIfExists('users');

Columns

Creating Columns

The table method on the Schema facade may be used to update existing tables.
Like the createmethod, the table method accepts two arguments: the name of the
table and a Closure that receives a Blueprint instance you may use to add columns
to the table:

Schema::table('users', function ($table) {


$table->string('email');
});

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 92

Available Column Types

Of course, the schema builder contains a variety of column types that you may
specify when building your tables:

Command Description

$table->boolean('confirmed'); BOOLEAN equivalent for the database.

$table->char('name', 4); CHAR equivalent with a length.

$table->dateTime('created_at'); DATETIME equivalent for the database.

$table->decimal('amount', 5, 2); DECIMAL equivalent with a precision and scale.

Incrementing ID (primary key) using a


$table->increments('id');
"UNSIGNED INTEGER" equivalent.

$table->string('email'); VARCHAR equivalent column.

$table->string('name', 100); VARCHAR equivalent with a length.

$table->text('description'); TEXT equivalent for the database.

Adds
$table->timestamps();
nullable created_at and updated_at columns.

Column Modifiers

In addition to the column types listed above, there are several column "modifiers"
you may use while adding a column to a database table. For example, to make the
column "nullable", you may use the nullable method:

Schema::table('users', function ($table) {


$table->string('email')->nullable();
});
Below is a list of all the available column modifiers. This list does not include
the index modifiers:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 93

Modifier Description

Place the column "after" another column


->after('column')
(MySQL Only)

->comment('my comment') Add a comment to a column

->default($value) Specify a "default" value for the column

Allow NULL values to be inserted into the


->nullable()
column

->unsigned() Set integer columns to UNSIGNED

Updating Column Attributes

The change method allows you to modify some existing column types to a new
type or modify the column's attributes. For example, you may wish to increase the
size of a string column. To see the change method in action, let's increase the size
of the name column from 25 to 50:

Schema::table('users', function ($table) {


$table->string('name', 50)->change();
});

We could also modify a column to be nullable:

Schema::table('users', function ($table) {


$table->string('name', 50)->nullable()->change();
});

Renaming Columns

To rename a column, you may use the renameColumn method on the Schema
builder. Before renaming a column, be sure to add the doctrine/dbal dependency
to your composer.json file:

Schema::table('users', function ($table) {


$table->renameColumn('from', 'to');
});

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 94

Dropping Columns

To drop a column, use the dropColumn method on the Schema builder. Before
dropping columns from a SQLite database, you will need to add
the doctrine/dbal dependency to your composer.jsonfile and run the composer
update command in your terminal to install the library:

Schema::table('users', function ($table) {


$table->dropColumn('votes');
});
You may drop multiple columns from a table by passing an array of column names
to the dropColumn method:

Schema::table('users', function ($table) {


$table->dropColumn(['votes', 'avatar', 'location']);
});

Indexes

Creating Indexes

The schema builder supports several types of indexes. First, let's look at an
example that specifies a column's values should be unique. To create the index,
we can simply chain the unique method onto the column definition:

$table->string('email')->unique();

Alternatively, you may create the index after defining the column. For example:

$table->unique('email');

You may even pass an array of columns to an index method to create a compound
index:

$table->index(['account_id', 'created_at']);

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 95

Laravel will automatically generate a reasonable index name, but you may pass a
second argument to the method to specify the name yourself:

$table->index('email', 'my_index_name');

Available Index Types

Command Description

$table->primary('id'); Add a primary key.

$table->primary(['first', 'last']); Add composite keys.

$table->unique('email'); Add a unique index.

$table->unique(['first', 'last']); Add a composite unique index.

$table->index('state'); Add a basic index.

Foreign Key Constraints

Laravel also provides support for creating foreign key constraints, which are used
to force referential integrity at the database level. For example, let's define
a user_id column on the posts table that references the id column on
a users table:

Schema::table('posts', function ($table) {


$table->integer('user_id')->unsigned();

$table->foreign('user_id')->references('id')->on('users');
});
You may also specify the desired action for the "on delete" and "on update"
properties of the constraint:

$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 96

To drop a foreign key, you may use the dropForeign method. Foreign key
constraints use the same naming convention as indexes. So, we will concatenate
the table name and the columns in the constraint then suffix the name with
"_foreign":

$table->dropForeign('posts_user_id_foreign');

Or, you may pass an array value which will automatically use the conventional
constraint name when dropping:

$table->dropForeign(['user_id']);

Database Seeding:

Laravel includes a simple method of seeding your database with test data using
seed classes. All seed classes are stored in the database/seeds directory. Seed
classes may have any name you wish, but probably should follow some sensible
convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is
defined for you. From this class, you may use the call method to run other seed
classes, allowing you to control the seeding order.

Writing Seeders

To generate a seeder, execute the make:seeder Artisan command. All seeders


generated by the framework will be placed in the database/seeds directory:

php artisan make:seeder UsersTableSeeder

A seeder class only contains one method by default: run. This method is called
when the db:seedArtisan command is executed. Within the run method, you may
insert data into your database however you wish. You may use the query
builder to manually insert data or you may use Eloquent model factories.
As an example, let's modify the default DatabaseSeeder class and add a database
insert statement to the run method:

<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 97

{
/**
* Run the database seeds. @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'@gmail.com',
'password' => bcrypt('secret'),
]);
}
}

Running Seeders

Once you have written your seeder classes, you may use the db:seed Artisan
command to seed your database. By default, the db:seed command runs
the DatabaseSeeder class, which may be used to call other seed classes. However,
you may use the --class option to specify a specific seeder class to run
individually:

php artisan db:seed

php artisan db:seed --class=UsersTableSeeder

You may also seed your database using the migrate:refresh command, which will
also rollback and re-run all of your migrations. This command is useful for
completely re-building your database:

php artisan migrate:refresh –seed

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 98

Unit – 3

Routing in Laravel

Basic Routing

The most basic Laravel routes simply accept a URI and a Closure, providing a very
simple and expressive method of defining routes:

Route::get('foo', function () {
return 'Hello World';
});

The Default Route Files


All Laravel routes are defined in your route files, which are located in
the routes directory. These files are automatically loaded by the framework.
The routes/web.php file defines routes that are for your web interface. These
routes are assigned the web middleware group, which provides features like
session state and CSRF protection. The routes in routes/api.php are stateless and
are assigned the api middleware group.

For most applications, you will begin by defining routes in


your routes/web.php file.

Available Router Methods


The router allows you to register routes that respond to any HTTP verb:

Route::get($uri, $callback);
Route::post($uri, $callback);
Route::put($uri, $callback);
Route::patch($uri, $callback);
Route::delete($uri, $callback);
Route::options($uri, $callback);

Sometimes you may need to register a route that responds to multiple HTTP
verbs. You may do so using the match method. Or, you may even register a route
that responds to all HTTP verbs using the any method:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 99

Route::match(['get', 'post'], '/', function () {


//
});
Route::any('foo', function () {
//
});

CSRF Protection
Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in
the web routes file should include a CSRF token field. Otherwise, the request will
be rejected. You can read more about CSRF protection in the CSRF
documentation:

<form method="POST" action="/profile">


{{ csrf_field() }}
...
</form>

Route Parameters

Required Parameters
Of course, sometimes you will need to capture segments of the URI within your
route. For example, you may need to capture a user's ID from the URL. You may
do so by defining route parameters:

Route::get('user/{id}', function ($id) {


return 'User '.$id;
});

You may define as many route parameters as required by your route:

Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId)


{
//
});

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 100

Route parameters are always encased within {} braces and should consist of
alphabetic characters. Route parameters may not contain a - character. Use an
underscore (_) instead.

Optional Parameters
Occasionally you may need to specify a route parameter, but make the presence
of that route parameter optional. You may do so by placing a ? mark after the
parameter name. Make sure to give the route's corresponding variable a default
value:

Route::get('user/{name?}', function ($name = null) {


return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});

Regular Expression Constraints


You may constrain the format of your route parameters using the where method
on a route instance. The where method accepts the name of the parameter and a
regular expression defining how the parameter should be constrained:

Route::get('user/{name}', function ($name) {


//
})->where('name', '[A-Za-z]+');

Route::get('user/{id}', function ($id) {


//
})->where('id', '[0-9]+');

Route::get('user/{id}/{name}', function ($id, $name) {


//
})->where(['id' => '[0-9]+', 'name' => '[a-z]+']);

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 101

Global Constraints
If you would like a route parameter to always be constrained by a given regular
expression, you may use the pattern method. You should define these patterns in
the boot method of your RouteServiceProvider:

/**
* Define your route model bindings, pattern filters, etc.
* @return void
*/
public function boot()
{
Route::pattern('id', '[0-9]+');
parent::boot();
}
Once the pattern has been defined, it is automatically applied to all routes using
that parameter name:
Route::get('user/{id}', function ($id) {
// Only executed if {id} is numeric...
});

Named Routes

Named routes allow the convenient generation of URLs or redirects for specific
routes. You may specify a name for a route by chaining the name method onto the
route definition:

Route::get('user/profile', function () {
//
})->name('profile');

You may also specify route names for controller actions:


Route::get('user/profile', 'UserController@showProfile')->name('profile');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 102

Generating URLs To Named Routes


Once you have assigned a name to a given route, you may use the route's name
when generating URLs or redirects via the global route function:

// Generating URLs...
$url = route('profile');

// Generating Redirects...
return redirect()->route('profile');

If the named route defines parameters, you may pass the parameters as the
second argument to the route function. The given parameters will automatically be
inserted into the URL in their correct positions:

Route::get('user/{id}/profile', function ($id) {


//
})->name('profile');

$url = route('profile', ['id' => 1]);

Route Groups

Route groups allow you to share route attributes, such as middleware or


namespaces, across a large number of routes without needing to define those
attributes on each individual route. Shared attributes are specified in an array
format as the first parameter to the Route::group method.

Middleware
To assign middleware to all routes within a group, you may use
the middleware key in the group attribute array. Middleware are executed in the
order they are listed in the array:

Route::group(['middleware' => 'auth'], function () {


Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 103

Sub-Domain Routing
Route groups may also be used to handle sub-domain routing. Sub-domains may
be assigned route parameters just like route URIs, allowing you to capture a
portion of the sub-domain for usage in your route or controller. The sub-domain
may be specified using the domain key on the group attribute array:

Route::group(['domain' => '{account}.myapp.com'], function () {


Route::get('user/{id}', function ($account, $id) {
//
});
});

Route Prefixes
The prefix group attribute may be used to prefix each route in the group with a
given URI. For example, you may want to prefix all route URIs within the group
with admin:

Route::group(['prefix' => 'admin'], function () {


Route::get('users', function () {
// Matches The "/admin/users" URL
});
});

Route Model Binding

When injecting a model ID to a route or controller action, you will often query to
retrieve the model that corresponds to that ID. Laravel route model binding
provides a convenient way to automatically inject the model instances directly into
your routes. For example, instead of injecting a user's ID, you can inject the
entire User model instance that matches the given ID.

Implicit Binding
Laravel automatically resolves Eloquent models defined in routes or controller
actions whose variable names match a route segment name. For example:

Route::get('api/users/{user}', function (App\User $user) {


return $user->email;
});

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 104

In this example, since the Eloquent $user variable defined on the route matches
the {user}segment in the route's URI, Laravel will automatically inject the model
instance that has an ID matching the corresponding value from the request URI. If
a matching model instance is not found in the database, a 404 HTTP response will
automatically be generated.

Explicit Binding

To register an explicit binding, use the router's model method to specify the class
for a given parameter. You should define your explicit model bindings in
the boot method of the RouteServiceProvider class:

public function boot()


{
parent::boot();
Route::model('user', App\User::class);
}
Next, define a route that contains a {user} parameter:
Route::get('profile/{user}', function (App\User $user) {
//
});
Since we have bound all {user} parameters to the App\User model,
a User instance will be injected into the route. So, for example, a request
to profile/1 will inject the User instance from the database which has an ID of 1.

If a matching model instance is not found in the database, a 404 HTTP response
will be automatically generated.

The routing mechanism is depicted in the following image:

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 105

Let us now understand the steps in detail:


 Step 1: First, we need to execute the root URL of the application.

 Step 2: The executed URL will match with the appropriate method in the
route.php file. In our case, it will match to get the method and the root (‗/‘)
URL. This will execute the related function.

 Step 3: The function calls the template file


resources/views/welcome.blade.php. The function later calls the
view() function with argument ‘welcome’ without using the blade.php. It
will produce the following HTML output.

Throwing 404 Error:

In Laravel all the exceptions are handled by app\Exceptions\Handler class. This


class contains two methods — report and render.

report() method

report() method is used to report or log exception. It is also used to send log
exceptions to external services like Sentry, Bugsnag etc.

render() method

render() method is used to render an exception into an HTTP response which will
be sent back to browser.

Beside these two methods, the app\Exceptions\Handler class contains an


important property called ―$dontReport‖. This property takes an array of exception
types that will not be logged.

HTTP Exceptions

Some exceptions describe HTTP error codes like 404, 500 etc. To generate such
response anywhere in an application, you can use abort() method as follows.
abort(404)

Custom Error pages

Laravel makes it very easy for us to use the custom error pages for each separate
error codes. For example, if you want to design custom page for error code 404,
you can create a view at resources/views/errors/404.blade.php. Same way, if you

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 106

want to design error page for error code 500, it should be stored at
resources/views/errors/500.blade.php.

Example
Step 1: Add the following lines in app/Http/routes.php.

app/Http/routes.php

Route::get('/error',function(){
abort(404);
});

code in that file.


resources/views/errors/404.blade.php
<!DOCTYPE html>
<html>
<head>
<title>404</title>
<link href="https://fonts.googleapis.com/css?family=Lato:100"
rel="stylesheet" type="text/css">

<style>
html, body {
height: 100%;
}
body {
margin: 0;
padding: 0;
width: 100%;
color: #B0BEC5;
display: table;
font-weight: 100;
font-family: 'Lato';
}
.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.content {
text-align: center;
display: inline-block;
}
font-size: 72px;
margin-bottom: 40px;
}
</style>
</head>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 107

<body>
<div class="container">
<div class="content">
<div class="title">404 Error</div>
</div>
</div>
</body>
</html>

Step 3: Visit the following URL to test the event.


http://localhost:8000/error

Step 4: After visiting the URL, you will receive the following output:

Routing to Controller:

Basic Controllers

Instead of defining all of your route-level logic in a single routes.php file, you may
wish to organize this behavior using Controller classes. Controllers can group
related route logic into a class, as well as take advantage of more advanced
framework features such as automatic dependency injection.

Controllers are typically stored in the app/controllers directory, and this directory
is registered in the classmap option of your composer.json file by default.
However, controllers can technically live in any directory or any sub-directory.
Route declarations are not dependent on the location of the controller class file on
disk. So, as long as Composer knows how to autoload the controller class, it may
be placed anywhere you wish.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 108

Here is an example of a basic controller class:

class UserController extends BaseController {

/**
* Show the profile for the given user.
*/
public function showProfile($id)
{
$user = User::find($id);
return View::make('user.profile', array('user' => $user));
}
}
All controllers should extend the BaseController class. The BaseController is also
stored in the app/controllers directory, and may be used as a place to put shared
controller logic. The BaseController extends the framework's Controller class. Now,
we can route to this controller action like so:

Route::get('user/{id}', 'UserController@showProfile');

If you choose to nest or organize your controller using PHP namespaces, simply
use the fully qualified class name when defining the route:

Route::get('foo', 'Namespace\FooController@method');

Note: Since we're using Composer to auto-load our PHP classes, controllers may
live anywhere on the file system, as long as composer knows how to load them.
The controller directory does not enforce any folder structure for your application.
Routing to controllers is entirely de-coupled from the file system.
You may also specify names on controller routes:

Route::get('foo', array('uses' => 'FooController@method',


'as' => 'name'));

To generate a URL to a controller action, you may use the URL::action method or
the action helper method:

$url = URL::action('FooController@method');

$url = action('FooController@method');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 109

You may access the name of the controller action being run using
the currentRouteAction method:

$action = Route::currentRouteAction();

Controller Filters

Filters may be specified on controller routes similar to "regular" routes:

Route::get('profile', array('before' => 'auth',


'uses' => 'UserController@showProfile'));
However, you may also specify filters from within your controller:
class UserController extends BaseController {
/**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter('auth', array('except' => 'getLogin'));

$this->beforeFilter('csrf', array('on' => 'post'));

$this->afterFilter('log', array('only' =>


array('fooAction', 'barAction')));
}

You may also specify controller filters inline using a Closure:


class UserController extends BaseController {
/**
* Instantiate a new UserController instance.
*/
public function __construct()
{
$this->beforeFilter(function()
{
//
});
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 110

If you would like to use another method on the controller as a filter, you may
use @ syntax to define the filter:

class UserController extends BaseController {


// Instantiate a new UserController instance.

public function __construct()


{
$this->beforeFilter('@filterRequests');
}
// Filter the incoming requests.

public function filterRequests($route, $request)


{
//
}
}

Implicit Controllers

Laravel allows you to easily define a single route to handle every action in a
controller. First, define the route using the Route::controller method:

Route::controller('users', 'UserController');

The controller method accepts two arguments. The first is the base URI the
controller handles, while the second is the class name of the controller. Next, just
add methods to your controller, prefixed with the HTTP verb they respond to:

class UserController extends BaseController {


public function getIndex()
{
//
}
public function postProfile()
{
//
}

public function anyLogin()


{
//
}
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 111

RESTful Resource Controllers

Resource controllers make it easier to build RESTful controllers around resources.


For example, you may wish to create a controller that manages "photos" stored by
your application. Using the controller:make command via the Artisan CLI and
the Route::resource method, we can quickly create such a controller.

To create the controller via the command line, execute the following command:

php artisan controller:make PhotoController

Now we can register a resourceful route to the controller:

Route::resource('photo', 'PhotoController');

This single route declaration creates multiple routes to handle a variety of RESTful
actions on the photo resource. Likewise, the generated controller will already have
stubbed methods for each of these actions with notes informing you which URIs
and verbs they handle.

Actions Handled By Resource Controller


Verb Path Action Route Name

GET /resource index resource.index

GET /resource/create create resource.create

POST /resource store resource.store

GET /resource/{resource} show resource.show

GET /resource/{resource}/edit edit resource.edit

PUT/PATCH /resource/{resource} update resource.update

DELETE /resource/{resource} destroy resource.destroy

Sometimes you may only need to handle a subset of the resource actions:

php artisan controller:make PhotoController --only=index,show

php artisan controller:make PhotoController --except=index

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 112

And, you may also specify a subset of actions to handle on the route:

Route::resource('photo', 'PhotoController',
array('only' => array('index', 'show')));
Route::resource('photo', 'PhotoController',
array('except' => array('create', 'store', 'update', 'destroy')));

By default, all resource controller actions have a route name; however, you can
override these names by passing a names array with your options:

Route::resource('photo', 'PhotoController',
array('names' => array('create' => 'photo.build')));

Adding Additional Routes To Resource Controllers


If it becomes necessary for you to add additional routes to a resource controller
beyond the default resource routes, you should define those routes before your
call to Route::resource:

Route::get('photos/popular', 'PhotoController@method');
Route::resource('photos', 'PhotoController');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 113

Unit – 4

Blade Template

Introduction

Blade is the simple, yet powerful templating engine provided with Laravel. Unlike
other popular PHP templating engines, Blade does not restrict you from using plain
PHP code in your views. In fact, all Blade views are compiled into plain PHP code
and cached until they are modified, meaning Blade adds essentially zero overhead
to your application. Blade view files use the .blade.php file extension and are
typically stored in the resources/views directory.

Template inheritance

In a nutshell, template inheritance allows us to define a master layout with


elements that are common to all web pages. The individual pages extend the
master layout. This saves us time of repeating the same elements in the individual
pages

Master layout

All blade templates must be saved with the .blade extension. In this section, we
are going to create a master template that all pages will extend. The following is
the syntax for defining a master layout.

1. create a new directory layout in /resources/views/


2. create a new file master.blade.php in
/resources/views/layouts/master.blade.php
3. add the following code to master.blade.php

<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show

<div class="container">
@yield('content')
</div>
</body>
</html>

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 114

HERE,

 @yield('title') is used to display the value of the title


 @section('sidebar') is used to define a section named sidebar
 @show is used to display the contents of a section
 @yield('content') is used to display the contents of content

Extending the master layout

We will now create a page that extends the master layout.

1. create a new page page.blade.php in /resources/views/page.blade.php


2. add the following code

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>


@endsection

@section('content')
<p>This is my body content.</p>
@endsection

HERE,

 @extends('layouts.master') extends the master layout


 @section('title', 'Page Title') sets the value of the title section.
 @section('sidebar') defines a sidebar section in the child page of master layout
 @parent displays the contents of the sidebar section that is defined in the master
layout
 <p>This is appended to the master sidebar.</p> adds paragraph content to the
sidebar section
 @endsection ends the sidebar section
 @section('content') defines the content section
 @section('content') adds paragraph content to the content section
 @endsection ends the content section

We will now add a route that tests our blade template

1. open /app/Http/routes.php
2. add the following route

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 115

Route::get('blade', function () { return view('page'); });

Save the changes

Load the following URL in your web browser

http://localhost/larashop/public/blade
You will get the following results

This is the master sidebar. This is appended to the master sidebar. This is my
body content.

Displaying variables in a blade template

In this section, we will define a name variable and pass it to our blade template
view

1. open /app/Http/routes.php
2. modify the blade route to the following

Route::get('blade', function () {
return view('page',array('name' => 'The Raven'));
});
Save the change

We will now update pages.blade.php is display the variable

1. Open /resources/views/page.blade.php
2. Update the contents to the following

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>


@endsection

@section('content')
<h2>{{$name}}</h2>
<p>This is my body content.</p>
@endsection

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 116

HERE,

• {{$name}} double opening curly braces and double closing curly braces are
used to display the value of $name variable.

Save the changes

Load the following URL in your web browser

http://localhost/larashop/public/blade

You will get the following results

Note: the value of $name has been displayed "The Raven"

Blade conditional statements

Blade also supports conditional statements. Conditional statements are used to


determine what to display in the browser. In this section, we will pass a variable
that will determine what to display in the browser.

1. Open /app/Http/routes.php
2. modify the blade route as follows

Route::get('blade', function () {
return view('page',array('name' => 'The Raven','day' => 'Friday'));
});

HERE,

 We added another variable day with a value of Friday.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 117

Save the changes

1. Open /resources/views/page.blade.php
2. Modify the code to the following

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>


@endsection

@section('content')
<h2>{{$name}}</h2>
<p>This is my body content.</p>
<h2>If Statement</h2>
@if ($day == 'Friday')
<p>Time to party</p>
@else
<p>Time to make money</p>
@endif
@endsection

HERE,

 @if ($day == 'Friday') starts the if statement and evaluates the


condition $day == 'Friday'
 <p>Time to party</p> is executed if the value of $day is Friday
 @else is the else part of the if statement
 @endif ends the if statement

Load the following URL in your browser

http://localhost/larashop/public/blade

You will get the following content at the end of the page Time to party

Blade Loops

Blade template supports all of the loops that PHP supports. In this section, we will
look at how we can use the foreach loop in blade to loop through an array of items

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 118

1. Open /app/Http/routes.php
2. Modify the code for the blade route to the following

Route::get('blade', function () {
$drinks = array('Vodka','Gin','Brandy');
return view('page',array('name' => 'The Raven','day' => 'Friday','drinks' => $d
rinks));
});

HERE,

 $drinks = array('Vodka','Gin','Brandy'); defines an array variable that we are


passing to the blade template

Save the changes

1. Open /resources/views/page.blade.php
2. Modify the contents to the following

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>


@endsection

@section('content')
<h2>{{$name}}</h2>
<p>This is my body content.</p>
<h2>If Statement</h2>
@if ($day == 'Friday')
<p>Time to party</p>
@else
<p>Time to make money</p>
@endif

<h2>Foreach Loop</h2>
@foreach ($drinks as $drink)
{{$drink}} <br>
@endforeach
@endsection

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 119

Load the following URL in your browser

http://localhost/larashop/public/blade

You will get the following content at the end of the page

Vodka
Gin
Brandy

Executing PHP functions in blade

In this section, we will call the PHP date function using blade.

1. Open /resources/views/page.blade.php
2. Modify the contents to the following

@extends('layouts.master')

@section('title', 'Page Title')

@section('sidebar')
@parent

<p>This is appended to the master sidebar.</p>


@endsection

@section('content')
<h2>{{$name}}</h2>
<p>This is my body content.</p>
<h2>If Statement</h2>
@if ($day == 'Friday')
<p>Time to party</p>
@else
<p>Time to make money</p>
@endif

<h2>Foreach Loop</h2>
@foreach ($drinks as $drink)
{{$drink}} <br>
@endforeach

<h2>Execute PHP Function</h2>


<p>The date is {{date(' D M, Y')}}</p>
@endsection

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 120

HERE,

 {{date(' D M, Y')}} double opening and closing curly braces are used to
execute the PHP date function.

Load the following URL in your browser

http://localhost/larashop/public/blade

You will get the following content at the end of the page

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 121

Unit – 5

Eloquent ORM

Eloquent ORM Models

Eloquent models are models that extend the Illuminate\Database\Eloquent\Model


class In the MVC architectural design, models are used to interact with data
sources. Eloquent ORM is an Object Relational Mapper developed by Laravel. It
implements the active record pattern and is used to interact with relational
databases. Eloquent ORM can be used inside Laravel or outside Laravel since it‘s a
complete package on its own. Models are Laravel 5 are located in
the /app directory.

Naming conventions
The law of the gods state that model names should be singular and table names
should be plural. Laravel automatically pluralizes the model name to get the table
name. But what if your language is Swahili and Laravel does not understand
Swahili?

Eloquent Models provide the above as the default implementation. You can
explicitly specify a table name if you want to. We will now create a model for the
categories table. The name of the model will be category. This is in accordance
with the law of the gods.

1. Open the command prompt and browser to the project root.


2. Run the following artisan command

php artisan make:model Category

HERE,

 php artisan make:model Category creates a model named Category


in /app/Category.php

Open the newly created model in /app/Category.php

You will get the following

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 122

class Category extends Model


{
//
}

HERE,

 use Illuminate\Database\Eloquent\Model; imports the Eloquent model class


namespace
 class Category extends Model defines a model Category that extends Model

Table name and primary key


By default, the plural form of the model name is used as the table name and the
primary key field name is assumed to be id. This section shows you how you can
explicitly define both the table and primary key field names Add the following lines
to Category model

protected $primaryKey = 'id';


protected $table = 'categories';

HERE,

 protected $primaryKey = 'id'; explicitly defines the primary key field name
 protected $table = 'categories'; explicitly defines the name of the table

Record timestamps
By default, Laravel assumes you have added the following fields to all of your
database tables

 created_at
 updated_at

These fields are updated whenever you create a new record or update an existing
record. If you do not want to use these timestamp fields in your database tables,
you can set the following property to turn them off.

public $timestamps = false;

HERE,

 public $timestamps = false; tells Eloquent ORM model not to consider


created_at and updated_at table fields.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 123

Laravel 5: Run raw SQL Statement


In this section, we will create a base model that extends the eloquent model.

ORM frameworks are great but I sometimes find querying data from multiple
tables a pain in a quite significant part of my body. The developers for Laravel
understand this and as such, they provided mechanisms for executing raw SQL
statements.

Our base model will contain methods for retrieving data using raw SQL statements
and for executing INSERT, UPDATE & DELETE. I strongly recommend against
executing raw INSERT, UPDATE, & DELETE for security reasons. If you have good
reason to do so then you should make sure you sanitize all user submitted data
before supplying it to the queries.

1. go to the command prompt


2. Run the following artisan command to create the BaseModel

php artisan make:model BaseModel

1. Open BaseModel.php in /app/BaseModel.php


2. Modify the contents of BaseModel.php to the following

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;

class BaseModel extends Model {

public function selectQuery($sql_stmt) {


return DB::select($sql_stmt);
}

public function sqlStatement($sql_stmt) {


DB::statement($sql_stmt);
}
}

HERE,

 namespace App; defines the namespace for our base model


 use Illuminate\Database\Eloquent\Model; imports the Eloquent ORM model
 use DB; imports the DB namespace

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 124

 public function selectQuery($sqlstmt) { return


DB::select($sqlstmtt); } defines a public
function selectQuery($sql_stmt). $sqlstmt is a string parameter that
contains the SQL statement to be executed. DB::select($sqlstmt) executes
the SQL statement
 public function sqlStatement($sqlstmt) {
DB::statement($sqlstmtt); } defines a public
function sqlStatement. $sqlstmt is a string parameter that contains the SQL
statement to be executed. DB::statement($sqlstmt) executes the SQL
statement

We will now use our model to add a record to the database.

1. Open /app/Category.php model


2. Modify the code to the following

<?php

namespace App;

class Category extends BaseModel {


protected $primaryKey = 'id';
protected $table = 'categories';
protected $fillable = array('name', 'created_at_ip', 'updated_at_ip');
}

HERE,

 namespace App; defines the model namespace


 class Category extends BaseModel defines the category class that extends
the BaseModel
 protected $primaryKey = 'id'; explicitly defines the primary key field name.
The default is id so in this case it‘s not really necessary to specify it.
Personally I prefer setting the name explicitly.
 protected $table = 'categories'; explicitly defines the table name. The default
is the plural form of the model name.
 protected $fillable = array('name', 'createdatipp', 'updatedatip'); defines
field names that can be mass assigned. This is a security measure that
ensures only authorized fieldnames are affected.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 125

Eloquent ORM INSERT

In this section, we will use the category model to add data to a record to the
database. For the sake of simplicity, we will do this from a route

1. open /app/Http/routes.php
2. add the following code

Route::get('/insert', function() {
App\Category::create(array('name' => 'Music'));
return 'category added';
});

HERE,

 App\Category::create(array('name' => 'Music')); executes the create static


function of the model. The array array('name' => 'Music') matches field
names to values. Eloquent model will use these values to generate the SQL
insert statement and execute it.
 return 'category added'; outputs category added in the web browser

Open your web browser

Load the following URL

http://localhost/larashop/public/insert

You will get the following result

category added

Eloquent ORM READ

In this section, we will use the category model to retrieve all categories from the
database.

1. open /app/Http/routes.php
2. add the following code

Route::get('/read', function() {
$category = new App\Category();

$data = $category->all(array('name','id'));

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 126

foreach ($data as $list) {


echo $list->id . ' ' . $list->name . '
';
}
});

HERE,

 $category = new App\Category(); creates an instance variable of Category


model
 $data = $category->all(array('name','id')); calls the all method of the
model. The array parameter array('name','id') is used to specified the
column names that the query should return. If left blank, then all columns
will be returned.
 foreach ($data as $list){…} loops through the returned results and displays
the rows in the browser.

Open your web browser

Load the following URL

http://localhost/larashop/public/read

You will get the results similar to the following

5 CLOTHING
4 FASHION
3 KIDS
1 MENS
16 Music
2 WOMENS

Eloquent ORM UPDATE

In this section, we will update a record using the id. Based on the above results,
we will update music category with id 16 to HEAVY METAL 1.
open /app/Http/routes.php 2. add the following code

Route::get('/update', function() {
$category = App\Category::find(16);
$category->name = 'HEAVY METAL';
$category->save();

$data = $category->all(array('name','id'));

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 127

foreach ($data as $list) {


echo $list->id . ' ' . $list->name . '
';
}
});

HERE,

 $category = App\Category::find(16); call find function of the model and


pass in 16 as the primary key parameter value. Eloquent will return a record
with primary key value 16
 $category->name = 'HEAVY METAL'; assigns the value HEAVY METAL to the
name field
 $category->save(); saves the changes made to the record
 $data = $category->all(array('name','id')); retrieves all the categories
 foreach ($data as $list){…} loops through all the records and display the
value in the web browser.

Open your web browser

Load the following URL

http://localhost/larashop/public/update

You will get the following results

5 CLOTHING
4 FASHION
16 HEAVY METAL
3 KIDS
1 MENS
2 WOMENS

Eloquent ORM DELETE

In this section, we will delete the category CLOTHING. 1.


open /app/Http/routes.php 2. Add the following code

Route::get('/delete', function() {
$category = App\Category::find(5);
$category->delete();

$data = $category->all(array('name','id'));

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 128

foreach ($data as $list) {


echo $list->id . ' ' . $list->name . '
';
}
});

HERE,

 $category->delete(); deletes the record that was retrieved via the find
method

Open your web browser

Load the following URL

http://localhost/larashop/public/delete

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 129

Unit – 5

Validation
To learn about Laravel's powerful validation features, let's look at a complete
example of validating a form and displaying the error messages back to the user.

Defining The Routes


First, let's assume we have the following routes defined in our routes/web.php file:

Route::get('post/create', 'PostController@create');

Route::post('post', 'PostController@store');

Of course, the GET route will display a form for the user to create a new blog post,
while the POSTroute will store the new blog post in the database.

Creating The Controller


Next, let's take a look at a simple controller that handles these routes. We'll leave
the store method empty for now:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller


{
/* Show the form to create a new blog post.
* @return Response
*/
public function create()
{
return view('post.create');
}
/* Store a new blog post.
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
// Validate and store the blog post...
}
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 130

Writing The Validation Logic


Now we are ready to fill in our store method with the logic to validate the new blog
post. If you examine your application's base controller
(App\Http\Controllers\Controller) class, you will see that the class uses
a ValidatesRequests trait. This trait provides a convenient validate method to all of
your controllers.

The validate method accepts an incoming HTTP request and a set of validation
rules. If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the proper error
response will automatically be sent back to the user. In the case of a traditional
HTTP request, a redirect response will be generated, while a JSON response will be
sent for AJAX requests.

To get a better understanding of the validate method, let's jump back into
the store method:

/**
* Store a new blog post.
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);

// The blog post is valid, store in database...


}
As you can see, we simply pass the incoming HTTP request and desired validation
rules into the validate method. Again, if the validation fails, the proper response
will automatically be generated. If the validation passes, our controller will
continue executing normally.

Displaying The Validation Errors


So, what if the incoming request parameters do not pass the given validation
rules? As mentioned previously, Laravel will automatically redirect the user back to
their previous location. In addition, all of the validation errors will automatically
be flashed to the session.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 131

Again, notice that we did not have to explicitly bind the error messages to the
view in our GET route. This is because Laravel will check for errors in the session
data, and automatically bind them to the view if they are available.
The $errors variable will be an instance of Illuminate\Support\MessageBag. For
more information on working with this object, check out its documentation.

The $errors variable is bound to the view by


the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by
the web middleware group. When this middleware is applied an $errors variable will always
be available in your views, allowing you to conveniently assume the $errors variable is always
defined and can be safely used.

So, in our example, the user will be redirected to our controller's create method
when validation fails, allowing us to display the error messages in the view:

<!-- /resources/views/post/create.blade.php -->

<h1>Create Post</h1>

@if (count($errors) > 0)


<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<!-- Create Post Form -->

Customizing The Error Format


If you wish to customize the format of the validation errors that are flashed to the
session when validation fails, override the formatErrors on your base request
(App\Http\Requests\Request). Don't forget to import
the Illuminate\Contracts\Validation\Validator class at the top of the file:

//{@inheritdoc}

protected function formatErrors(Validator $validator)


{
return $validator->errors()->all();
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 132

Customizing The Error Messages


You may customize the error messages used by the form request by overriding
the messagesmethod. This method should return an array of attribute / rule pairs
and their corresponding error messages:

/**
* Get the error messages for the defined validation rules.
*
* @return array
*/
public function messages()
{
return [
'title.required' => 'A title is required',
'body.required' => 'A message is required',
];
}

Manually Creating Validators

If you do not want to use the ValidatesRequests trait's validate method, you may
create a validator instance manually using the Validator facade. The make method
on the facade generates a new validator instance:

<?php

namespace App\Http\Controllers;

use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class PostController extends Controller


{
/**
* Store a new blog post.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 133

$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);

if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}

// Store the blog post...


}
}
The first argument passed to the make method is the data under validation. The
second argument is the validation rules that should be applied to the data.

After checking if the request validation failed, you may use the withErrors method
to flash the error messages to the session. When using this method,
the $errors variable will automatically be shared with your views after redirection,
allowing you to easily display them back to the user. The withErrors method
accepts a validator, a MessageBag, or a PHP array.

Working With Error Messages

After calling the errors method on a Validator instance, you will receive
an Illuminate\Support\MessageBag instance, which has a variety of convenient
methods for working with error messages. The $errors variable that is
automatically made available to all views is also an instance of
the MessageBag class.

Retrieving The First Error Message For A Field


To retrieve the first error message for a given field, use the first method:

$errors = $validator->errors();

echo $errors->first('email');

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 134

Retrieving All Error Messages For A Field


If you need to retrieve an array of all the messages for a given field, use
the get method:

foreach ($errors->get('email') as $message) {


//
}

Retrieving All Error Messages For All Fields


To retrieve an array of all messages for all fields, use the all method:

foreach ($errors->all() as $message) {


//
}

Determining If Messages Exist For A Field


The has method may be used to determine if any error messages exist for a given
field:

if ($errors->has('email')) {
//
}

Custom Error Messages


If needed, you may use custom error messages for validation instead of the
defaults. There are several ways to specify custom messages. First, you may pass
the custom messages as the third argument to the Validator::make method:

$messages = [
'required' => 'The :attribute field is required.',
];

$validator = Validator::make($input, $rules, $messages);

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 135

In this example, the :attribute place-holder will be replaced by the actual name of
the field under validation. You may also utilize other place-holders in validation
messages. For example:

$messages = [
'same' => 'The :attribute and :other must match.',
'size' => 'The :attribute must be exactly :size.',
'between' => 'The :attribute must be between :min - :max.',
'in' => 'The :attribute must be one of the following types: :values',
];

Specifying A Custom Message For A Given Attribute


Sometimes you may wish to specify a custom error messages only for a specific
field. You may do so using "dot" notation. Specify the attribute's name first,
followed by the rule:

$messages = [
'email.required' => 'We need to know your e-mail address!',
];

Available Validation Rules

Below is a list of all available validation rules and their function:

accepted
The field under validation must be yes, on, 1, or true. This is useful for validating
"Terms of Service" acceptance.

after:date
The field under validation must be a value after a given date. The dates will be
passed into the strtotime PHP function:

'start_date' => 'required|date|after:tomorrow'

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 136

Instead of passing a date string to be evaluated by strtotime, you may specify


another field to compare against the date:

'finish_date' => 'required|date|after:start_date'

alpha
The field under validation must be entirely alphabetic characters.

alpha_dash
The field under validation may have alpha-numeric characters, as well as dashes
and underscores.

alpha_num
The field under validation must be entirely alpha-numeric characters.

array
The field under validation must be a PHP array.

before:date
The field under validation must be a value preceding the given date. The dates will
be passed into the PHP strtotime function.

between:min,max
The field under validation must have a size between the given min and max.
Strings, numerics, and files are evaluated in the same fashion as the size rule.

boolean
The field under validation must be able to be cast as a boolean. Accepted input
are true, false, 1, 0, "1", and "0".

confirmed
The field under validation must have a matching field of foo_confirmation. For
example, if the field under validation is password, a
matching password_confirmation field must be present in the input.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 137

date
The field under validation must be a valid date according to the strtotime PHP
function.

date_format:format
The field under validation must match the given format. The format will be
evaluated using the PHP date_parse_from_format function. You should
use either date or date_format when validating a field, not both.

different:field
The field under validation must have a different value than field.

digits:value
The field under validation must be numeric and must have an exact length
of value.

digits_between:min,max
The field under validation must have a length between the given min and max.

distinct
When working with arrays, the field under validation must not have any duplicate
values.

'foo.*.id' => 'distinct'

email
The field under validation must be formatted as an e-mail address.

exists:table,column
The field under validation must exist on a given database table.

Basic Usage Of Exists Rule


'state' => 'exists:states'

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 138

file
The field under validation must be a successfully uploaded file.

filled
The field under validation must not be empty when it is present.

image
The file under validation must be an image (jpeg, png, bmp, gif, or svg)

in:foo,bar,...
The field under validation must be included in the given list of values.

integer
The field under validation must be an integer.

max:value
The field under validation must be less than or equal to a maximum value. Strings,
numerics, and files are evaluated in the same fashion as the size rule.

mimetypes:text/plain,...
The file under validation must match one of the given MIME types:

'video' => 'mimetypes:video/avi,video/mpeg,video/quicktime'

To determine the MIME type of the uploaded file, the file's contents will be read
and the framework will attempt to guess the MIME type, which may be different
from the client provided MIME type.

min:value
The field under validation must have a minimum value. Strings, numerics, and
files are evaluated in the same fashion as the size rule.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 139

nullable
The field under validation may be null. This is particularly useful when validating
primitive such as strings and integers that can contain null values.

not_in:foo,bar,...
The field under validation must not be included in the given list of values.

numeric
The field under validation must be numeric.

present
The field under validation must be present in the input data but can be empty.

required
The field under validation must be present in the input data and not empty. A field
is considered "empty" if one of the following conditions are true:

 The value is null.


 The value is an empty string.
 The value is an empty array or empty Countable object.
 The value is an uploaded file with no path.

same:field
The given field must match the field under validation.

size:value
The field under validation must have a size matching the given value. For string
data, valuecorresponds to the number of characters. For numeric
data, value corresponds to a given integer value. For an array, size corresponds to
the count of the array. For files, size corresponds to the file size in kilobytes.

string
The field under validation must be a string. If you would like to allow the field to
also be null, you should assign the nullable rule to the field.

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 140

Validating Arrays

Validating array based form input fields doesn't have to be a pain. For example, to
validate that each e-mail in a given array input field is unique, you may do the
following:

$validator = Validator::make($request->all(), [
'person.*.email' => 'email|unique:users',
'person.*.first_name' => 'required_with:person.*.last_name',
]);
Likewise, you may use the * character when specifying your validation messages
in your language files, making it a breeze to use a single validation message for
array based fields:

'custom' => [
'person.*.email' => [
'unique' => 'Each person must have a unique e-mail address',
]
],

Custom Validation Rules


Laravel provides a variety of helpful validation rules; however, you may wish to
specify some of your own. One method of registering custom validation rules is
using the extend method on the Validator facade. Let's use this method within
a service provider to register a custom validation rule:

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider


{
/** Bootstrap any application services.
* @return void
*/
public function boot()
{
Validator::extend('foo', function ($attribute, $value, $parameters,
$validator) {
return $value == 'foo';
});
}

CS-02 Advance Web Development in Laravel


TNRAO College of Information Technology - Rajkot 141

/** Register the service provider.


* @return void
*/
public function register()
{
//
}
}
The custom validator Closure receives four arguments: the name of
the $attribute being validated, the $value of the attribute, an array
of $parameters passed to the rule, and the Validator instance.

You may also pass a class and method to the extend method instead of a Closure:

Validator::extend('foo', 'FooValidator@validate');

Defining The Error Message


You will also need to define an error message for your custom rule. You can do so
either using an inline custom message array or by adding an entry in the
validation language file. This message should be placed in the first level of the
array, not within the custom array, which is only for attribute-specific error
messages:

"foo" => "Your input was invalid!",

"accepted" => "The :attribute must be accepted.",

// The rest of the validation error messages...

CS-02 Advance Web Development in Laravel

You might also like