Professional Documents
Culture Documents
CS-02 Laravel Final Material
CS-02 Laravel Final Material
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
The Basics:
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.
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.
<?php
class phpClass {
var $var1;
[..]
[..]
} ?>
The special form class followed by the name of the class that you want to
define.
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/>";
}
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.
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.
Following example shows how to set title and prices for the three books by calling
member functions.
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();
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.
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.
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->getPrice();
$chemistry->getPrice();
$maths->getPrice();
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 −
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.
Now apart from inherited functions, class Novel keeps two additional member
functions.
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 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.
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!");
}
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.
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!");
}
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.
interface Mail {
public function sendMail();
}
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.
class MyClass {
function __construct($incomingValue) {
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.
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).
<?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";
?>
class Name {
var $_firstName;
var $_lastName;
NOTE − A constructor can be defined with the same name as the name of a
class. It is defined in above example.
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).
<?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.
<?php
class OtherClass extends MyClass
{
public static $my_static = 'static var';
$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.
<?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";
}
}
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.
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.
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
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.
interface Mail {
public function sendMail();
}
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';
}
}
}
$object = new namedClass( 'Student' );
echo $object -> returnProperty( 'className' ) . "<br>"; // Named
echo $object -> returnProperty( 'classProp' ); // I am a class property
?>
Object Iteration:
As the output shows, the foreach iterated through all of the visible properties
that could be accessed.
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';
function iterateVisible() {
foreach ($this as $key => $value) {
echo "$key => $value <br>";
}
}
}
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 object of your class attempts to set value of
__set
the property which is really inaccessible or unavailable in your class.
__call magic method trigger when you are attempting to call method or
__call
function of the class which is either inaccessible or unavailable.
__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.
class test
{
function __construct()
{
echo 1;
}
function __destruct()
{
echo 2;
}
$objT = new test(); //__construct get automatically executed and print 1 on screen
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.
<?php
class BaseClass {
public function test() {
echo "BaseClass::test() 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.
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.
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.
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.
<?php
// Example of Copy Object with reference
class Customer {
private $name;
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";
$c2->setName("Vishal");
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";
$c2->setName("Vishal");
echo $c1->getName()."<br>";
echo $c2->getName()."<br><br>";
?>
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.
<?php
function bool2str($bool)
{
if ($bool == false) {
return 'FALSE';
} else {
return 'TRUE';
}
}
class Class1
{
public $flag;
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.
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:
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
<?php
$models = array(
array('Toyota', 12, 44),
array('BMW', 13, 41)
);
?>
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:
<?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
<?php
class Vehicle {
public function color() {
echo 'car color is RED';
}
}
But, have you heard of another binding called ―Late Static Binding‖!! No…. then
let‘s go through that :) with some interesting example.
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();
}
}
function classname(){
return __CLASS__;
}
}
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.
<?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;
function foo($obj) {
// ($obj) = ($e) = <id>
$obj->foo = 2;
}
foo($e);
echo $e->foo."\n";
?>
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.
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.
Provides a clean and uniform solution for building an interface for developers.
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.
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.
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:
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.
The files under less/, js/, and fonts/ are the source code for Bootstrap CSS, JS,
and icon fonts (respectively).
HTML Template:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 101 Template</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 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>
<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>
What is a Grid?
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.
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.
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.
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.
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.
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 Options
The following table summarizes aspects of how Bootstrap grid system works
across multiple devices:
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:
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.)
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>
<div class="col-xs-6 col-sm-3" style="background-color: #dedef8;box-shadow:
inset 1px -1px 1px #444, inset -1px 1px 1px #444;">
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.
<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>
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="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>
</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>
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>
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.
The point is: with responsive design, the website automatically adjusts based on the
device the viewer sees it in.
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">
<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>
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:
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>):
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:
All textual <input>, <textarea>, and <select> elements with class .form-control have a width
of 100%
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
<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>
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:
<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>
Bootstrap Buttons
Button Styles
Bootstrap provides seven styles of buttons:
.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:
.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>
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:
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">
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.
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.
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>
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:
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):
Dropdown Position
Dropdown Right Example
To right-align the dropdown, add the .dropdown-menu-right class to the element with .dropdown-
menu:
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">
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 allows you to group a series of buttons together (on a single line) in a button group:
AppleSamsungSony
<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-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>
Note: For <button> elements, you must wrap each button in a .btn-group class:
With Bootstrap, a navigation bar can extend or collapse, depending on the screen size.
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>
The following example adds a dropdown menu for the "Page 1" button:
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).
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:
<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>
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:
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:
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="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>
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>
<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>
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>
Bootstrap Wells
Wells
The .well class adds a rounded border around an element with a gray background color and some
padding:
Well Size
Change the size of the well by adding the .well-sm class for small wells or .well-lg class for
large wells:
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
Note: Carousels are not supported properly in Internet Explorer 9 and earlier (because they use
CSS3 transitions and animations to achieve the slide effect).
<div class="item">
<img src="img_flower2.jpg" alt="Flower">
</div>
</div>
Example Explained
The outermost <div>:
Carousels require the use of an id (in this case id="myCarousel") for carousel controls to function
properly.
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 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 data-slide-to attribute specifies which slide to go to, when clicking on the specific dot.
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.
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.
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.
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 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)
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
Select use composer here. You will get the following command prompt window
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.
database
username
password
'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,
],
'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,
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:
• 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
• Control
The developer has the option to write her/his business logic either in Routers
or Controllers.
Root Directory
The root directory of Laravel contains various folders and files as shown in the
following figure.
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.
App 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.
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.
Unit – 2
Installation
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 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.
Server Requirements
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
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:
Config::get('app.timezone');
You may also specify a default value to return if the configuration option does not exist:
Config::set('database.default', 'sqlite');
Configuration values that are set at run-time are only set for the current request,
Environment Configuration
You may also pass arguments to the environment method to check if the environment
matches a given value:
if (App::environment('local'))
{
// The environment is local
}
if (App::environment('local', 'staging'))
{
// The environment is either local OR staging...
}
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.
<?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:
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.
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.
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()
});
If the Closure passed to the down method returns NULL, maintenance mode will be
ignored for that request.
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
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.
SQLite Configuration
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
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' => '',
],
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>
Unit – 3
Artisan
Introduction
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:
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
Next, you will need to register the command before it can be executed via the
Artisan CLI.
Command Structure
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.
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
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.
The Laravel Schema facade provides database agnostic support for creating and
manipulating tables across all of Laravel's supported database systems.
Artisan command:
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:
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:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
Running Migrations
To run all of your outstanding migrations, execute the migrate Artisan command:
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:
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:
The migrate:reset command will roll back all of your application's migrations:
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:
Of course, when creating the table, you may use any of the schema
builder's column methods to define the table's columns.
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')) {
//
}
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:
Of course, the schema builder contains a variety of column types that you may
specify when building your tables:
Command Description
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:
Modifier Description
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:
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:
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:
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']);
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');
Command Description
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:
$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');
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
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
{
/**
* 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:
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:
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';
});
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:
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:
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 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:
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');
// 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 Groups
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:
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 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:
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:
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:
If a matching model instance is not found in the database, a 404 HTTP response
will be automatically generated.
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.
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.
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)
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
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);
});
<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>
<body>
<div class="container">
<div class="content">
<div class="title">404 Error</div>
</div>
</div>
</body>
</html>
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.
/**
* 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:
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');
You may access the name of the controller action being run using
the currentRouteAction method:
$action = Route::currentRouteAction();
Controller Filters
If you would like to use another method on the controller as a filter, you may
use @ syntax to define the filter:
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:
To create the controller via the command line, execute the following command:
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.
Sometimes you may only need to handle a subset of the resource actions:
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')));
Route::get('photos/popular', 'PhotoController@method');
Route::resource('photos', 'PhotoController');
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
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.
<html>
<head>
<title>@yield('title')</title>
</head>
<body>
@section('sidebar')
This is the master sidebar.
@show
<div class="container">
@yield('content')
</div>
</body>
</html>
HERE,
@extends('layouts.master')
@section('sidebar')
@parent
@section('content')
<p>This is my body content.</p>
@endsection
HERE,
1. open /app/Http/routes.php
2. add the following route
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.
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
1. Open /resources/views/page.blade.php
2. Update the contents to the following
@extends('layouts.master')
@section('sidebar')
@parent
@section('content')
<h2>{{$name}}</h2>
<p>This is my body content.</p>
@endsection
HERE,
• {{$name}} double opening curly braces and double closing curly braces are
used to display the value of $name variable.
http://localhost/larashop/public/blade
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,
1. Open /resources/views/page.blade.php
2. Modify the code to the following
@extends('layouts.master')
@section('sidebar')
@parent
@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,
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
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,
1. Open /resources/views/page.blade.php
2. Modify the contents to the following
@extends('layouts.master')
@section('sidebar')
@parent
@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
http://localhost/larashop/public/blade
You will get the following content at the end of the page
Vodka
Gin
Brandy
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('sidebar')
@parent
@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
HERE,
{{date(' D M, Y')}} double opening and closing curly braces are used to
execute the PHP date function.
http://localhost/larashop/public/blade
You will get the following content at the end of the page
Unit – 5
Eloquent ORM
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.
HERE,
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
HERE,
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.
HERE,
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.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use DB;
HERE,
<?php
namespace App;
HERE,
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,
http://localhost/larashop/public/insert
category added
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'));
HERE,
http://localhost/larashop/public/read
5 CLOTHING
4 FASHION
3 KIDS
1 MENS
16 Music
2 WOMENS
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'));
HERE,
http://localhost/larashop/public/update
5 CLOTHING
4 FASHION
16 HEAVY METAL
3 KIDS
1 MENS
2 WOMENS
Route::get('/delete', function() {
$category = App\Category::find(5);
$category->delete();
$data = $category->all(array('name','id'));
HERE,
$category->delete(); deletes the record that was retrieved via the find
method
http://localhost/larashop/public/delete
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.
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.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
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',
]);
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.
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:
<h1>Create Post</h1>
//{@inheritdoc}
/**
* 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',
];
}
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;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
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.
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.
$errors = $validator->errors();
echo $errors->first('email');
if ($errors->has('email')) {
//
}
$messages = [
'required' => 'The :attribute field is required.',
];
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',
];
$messages = [
'email.required' => 'We need to know your e-mail address!',
];
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:
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.
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.
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.
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:
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.
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:
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.
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',
]
],
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;
You may also pass a class and method to the extend method instead of a Closure:
Validator::extend('foo', 'FooValidator@validate');