Professional Documents
Culture Documents
Laravel Tutorial
Laravel Tutorial
Laravel
Audience
This tutorial will guide the developers and students who want to learn how to develop a
website using Laravel. This tutorial is particularly m eant for all those developers who have
no prior experience of using Laravel.
Prerequisites
Before you start proceeding with this tutorial, we assum e that you are fam iliar with HTML,
C ore PHP, and Advance PHP. W e have used Laravel version 5.1 in all the exam ples.
All the content and graphics published in this e -book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e -book is prohibited to reuse, reta in, copy, distribute or republish
any contents or a part of contents of this e -book in any m anner without written consent
of the publisher.
W e strive to update the contents of our website and tutorials as tim ely and as precisely as
possible, however, the contents m ay contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, tim eliness or com ple teness of our
website or its contents including this tutorial. I f you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com
i
Laravel
Table of Contents
About the Tutorial........................................................................................................................................................... i
Audience ........................................................................................................................................................................... i
Prerequisites .................................................................................................................................................................... i
Features of Laravel.........................................................................................................................................................1
App ....................................................................................................................................................................................5
Bootstrap .........................................................................................................................................................................7
Config ................................................................................................................................................................................7
Database ..........................................................................................................................................................................7
Public ................................................................................................................................................................................8
Resources .........................................................................................................................................................................8
Storage..............................................................................................................................................................................8
Tests ..................................................................................................................................................................................8
Vendor ..............................................................................................................................................................................8
4. LARAVEL – CONFIGURATION.......................................................................... 10
Example ......................................................................................................................................................................... 20
Registering Middleware............................................................................................................................................. 21
Declaration of namespace......................................................................................................................................... 31
Controller Middleware............................................................................................................................................... 36
Method Injection......................................................................................................................................................... 47
iii
Laravel
Basic Response............................................................................................................................................................. 59
Attaching Headers....................................................................................................................................................... 59
Example ......................................................................................................................................................................... 62
Delete Records............................................................................................................................................................. 82
Errors.............................................................................................................................................................................. 86
Logging........................................................................................................................................................................... 86
Example ......................................................................................................................................................................... 95
iv
Laravel
Implementation......................................................................................................................................................... 134
Command.................................................................................................................................................................... 137
v
Laravel
vi
1. Laravel – Overview Laravel
Laravel is an open-source PHP fram ework, which is robust and easy to understand. It
follows a m odel-view-controller design pattern. Laravel reuses the existing com ponents of
different fram eworks which helps in creating a web application. The web applicatio n thus
designed is m ore structured and pragm atic.
Laravel offers a rich set of functionalities which incorporates the basic features of PHP
fram eworks like C odeIgniter, Yii and other program ming languages like R uby on Rails.
Laravel has a very rich set of features which will boost the speed of web developm ent.
I f you are fam iliar with C ore PHP and Advanced PHP, Laravel will m ake your task easier.
I t save s a lot tim e if you are planning to develop a website from scratch. Moreover, a
website built in Laravel is secure and prevents several web attacks.
Advantages of Laravel
Laravel offers you the following advantages, when you are designing a web application
based on it:
The web application becomes more scalable, owing to the Laravel fram ework .
C onsiderable tim e is saved in designing the web application, since Laravel reuses
the com ponents from other fram ework in developing web application .
I t includes nam espaces and interfaces, thus helps to organize and m anage
resources.
Composer
C om poser is a tool which includes all the dependencies and libraries. I t allows a user to
create a project with respect to the m entioned fram ework (for exam ple, those used in
Laravel installation). Third party libraries can be installed easily with help o f com poser.
All the dependencies are noted in composer.json file which is placed in the source folder.
Artisan
C om mand line interface used in Laravel is called Artisan. I t includes a set of com m ands
which assists in building a web application. These com m ands are incorporated from
Sym phony fram ework, resulting in add -on features in Laravel 5.1 (latest version of
Laravel).
Features of Laravel
Laravel offers the following key features which m akes it an ideal choice for designing web
applications:
Modularity
Laravel provides 20 built in libraries and m odules which helps in enhancement of the
1
Laravel
application. Every m odule is integrated with C om poser dependency m anager which eases
updates.
Testability
Laravel includes features and helpers which helps in testing through various test cases.
This feature helps in m aintaining the code as per the requirem ents.
Routing
Laravel provides a flexible approach to the user to define routes in the web application.
R outing helps to scale the application in a better way and increases its perform ance.
Configuration Management
A web application designed in Laravel will be running on different environm ents, which
m eans that there will be a constant change in its configuration. Laravel provides a
consistent approach to handle the configuration in an efficient way.
Schema Builder
Schem a Builder m aintains the database definitions and schema in PHP code. I t also
m aintains a track of changes with respect to database m igrations.
Template Engine
Laravel uses the Blade Template engine, a lightweight tem plate language used to
design hierarchical blocks and layouts with predefined blocks that include dynamic
content.
E-mail
Laravel includes a mail class which helps in sending m ail with rich content and
attachm ents from the web application.
Authentication
U ser authentication is a com m on feature in web applications. Laravel eases designing
authentication as it includes features such as register, forgot password and send
password reminders.
Redis
Laravel uses Redis to connect to an existing session and general-purpose cache. R edis
interacts with session directly.
Queues
Laravel includes queue services like em ailing large num ber of users or a specified Cron
job. These queues help in com pleting tasks in an easier m anner without waiting for the
previous task to be com pleted.
2
2. Laravel – Installation Laravel
For m anaging dependencies, Laravel uses composer. Make sure you have a Com poser
installed on your system before you install Laravel. I n this chapter, you will see the
installation process of Laravel. You will have to follow the steps given below for insta lling
Laravel onto your system :
Step 1: Visit the following U R L and download com poser to install it on your system .
https://getcomposer.org/download/
Step 2: After the C om poser is installed, check the installation by typing the C omposer
com m and in the com m and prom pt as shown in the following screenshot.
Step 3: C reate a new directory anywhere in your system for your new Laravel project.
After that, m ove to path where you have created the new directory and type the following
com m and there to install Laravel.
3
Laravel
Step 4: The above com mand will install Laravel in the current directory. Start the Laravel
service by executing the following com mand.
Step 5: After executing the above com mand, you will see a screen as shown below:
Step 6: C opy the U RL underlined in gray in the above screenshot and open that URL in
the browser. I f you see the following screen, it im plies Laravel has been installed
successfully.
4
3. Laravel – Application Structure Laravel
The application structure in Laravel is basically the structure of folders, sub -folders and
files included in a project. O nce we create a project in Laravel, we get an overview o f the
application structure as shown in the im age here.
The snapshot shown here refers to the root folder of Laravel nam ely laravel-project. It
includes various sub -folders and files. The analysis of folders and files, along with their
functional aspects is given below:
App
I t is the application folder and includes the entire source code of the project. I t contains
events, exceptions and m iddleware declaration. The app folder com prises various sub
folders as explained below:
Console
Console includes the artisan commands necessary for Laravel. It includes a directory named
5
Laravel
Commands, where all the commands are declared with the appropriate signature. The file
Kernal.php calls the commands declared in Inspire.php.
I f we need to call a specific com mand in Laravel, then we should m ake appropriate changes
in this directory.
Events
This folder includes all the events for the project.
Events are used to trigger activities, raise errors or necessary validations and provide
greater flexibility. Laravel keeps all the events under one directory. The default file
included is event.php where all the basic events are declared.
Exceptions
This folder contains all the m ethods needed to handle exceptions. I t also contains the file
handle.php that handles all the exceptions.
Http
The Http folder has sub-folders for controllers, m iddleware and application requests. As
Laravel follows the MVC design pattern, this folder includes m odel, controllers and views
defined for the specific directories.
The Middleware sub-folder includes m iddleware m echanism, com prising the filter
m echanism and communication between response and request.
Jobs
The Jobs directory m aintains the activities queued for Laravel application. The base class
is shared am ong all the Jobs and provides a central location to place them under one roof.
Listeners
Listeners are event-dependent and they include m ethods which are used to handle events
and exceptions. For example, the login event declared includes a LoginListener event.
Policies
Policies are the PHP classes which includes the authorization logic. Laravel includes a
feature to create all authorization logic within policy classes inside this sub folder.
6
Laravel
Providers
This folder includes all the service providers required to register events for core servers
and to configure a Laravel application.
Bootstrap
This folder encloses all the application bootstrap scripts. I t contains a sub-folder nam ely
cache, which includes all the files associated for caching a web application. Y ou can also
find the file app.php, which initializes the scripts necessary for bootstrap.
Config
The config folder includes various configurations and associated param eters required for
the sm ooth functioning of a Laravel application. Various files inclu ded within the config
folder are as shown in the im age here. The filenames work as per the functionality
associated with them .
Database
As the nam e suggests, this directory includes various param eters for database
functionalities. I t includes three sub-directories as given below:
Seeds: This contains the classes used for unit testing database.
Migrations: This folder helps in queries for m igrating the database used in the
web application.
Factories: This folder is used to generate large num ber of data records.
7
Laravel
Public
I t is the root folder which helps in initializing the Laravel application. I t includes the
following files and folders:
Resources
R esources directory contains the files which enhances your web application. The sub -
folders included in this directory and their purpose is explained below:
assets: The assets folder include files such as LESS and SC SS, that are required
for styling the web application.
views: Views are the HTML files or tem plates which interact with end users and
play a prim ary role in MVC architecture.
Storage
This is the folder that stores all the logs and necessary files which are needed frequently
when a Laravel project is running. The sub -folders included in this directory and their
purpose is given below:
app: This folder contains the files that are called in succession.
framework: I t contains sessions, cache and views which are called frequently.
Logs: All exceptions and error logs are tracked in this sub folder.
Tests
All the unit test cases are included in this directory. The nam ing convention for nam ing
test case classes is camel_case and follows the convention as per the functionality of the
class.
Vendor
Laravel is com pletely based on C om poser dependencies, for example to install Laravel
setup or to include third party libraries, etc. The Vendor folder includes all the com poser
dependencies.
8
Laravel
I n addition to the above m entioned files, Laravel also includes som e other files whi ch play
a prim ary role in various functionalities such as GitHub configuration, packages and third
party libraries.
9
4. Laravel – Configuration Laravel
I n the previous chapter, we have seen that the basic configuration files of Laravel are
included in the config directory. I n this chapter, let us discuss the categories included in
the configuration.
Environment Configuration
Environm ent variables are those which provide a list of web services to your web
application. All the environm ent variables are declared in the .env file which includes the
param eters required for initializing the configuration.
APP_ENV=local
APP_DEBUG=true
APP_KEY=base64:ZPt2wmKE/X4eEhrzJU6XX4R93rCwYG8E2f8QUA7kGK8=
APP_URL=http://localhost
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.ioMAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
10
Laravel
Important Points
W hile working with basic configuration files of Laravel, the following points are to be noted:
The .env file should not be committed to the application source control, since each
developer or user has some predefined environment configuration for the web
application.
For backup options, the development team should include the .env.example file,
which should contain the default configuration.
env-helper functions are called in the app.php file included in the config folder. The
above given example is calling for the basic local param eter.
For exam ple, to set the default tim e zone, the following code is used:
Caching of Configuration
To increase the perform ance and to boost the web application, it is im portant to cache all
the configuration values. The com mand for caching the configuration values is:
config:cache
11
Laravel
Maintenance Mode
Som etim es you m ay need to update some configuration values or perform m aintenance
on your website. I n such cases, keeping it in maintenance mode, m akes it easier for
you. Such web applications which are kept in m aintenance m ode , throw an exception
nam ely MaintenanceModeException with a status code of 503.
You can enable the m aintenance m ode on your Laravel web application using the following
com m and:
12
Laravel
The following screenshot shows how the web application looks when it is down:
O nce you finish working on updates and other m aintenance, you can disable the
m aintenance m ode on your web application using following com mand:
php artisan up
13
Laravel
Now, you can find that the website shows the output with proper functioning and
depicting that the m aintenance m ode is now rem oved as shown below:
14
5. Laravel – Routing Laravel
I n Laravel, a ll requests are m apped with the help of routes. Basic routing routes the
request to the associated controllers. This chapter discusses routing in Laravel.
Basic Routing
Route parameters
Named Routes
Basic Routing
All the application routes are registered within the app/routes.php file. This file tells
Laravel for the U RIs it should respond to and the associated controller will give it a
particular call. The sam ple route for the welcom e page can be seen as shown in the
screenshot given below:
return view('welcome');});
Example
O bserve the following example to understand m ore about R outing:
app/Http/routes.php
<?php
Route:get('/', function () {
15
Laravel
return view('welcome');
});
resources/view/welcome.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel</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%;
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;
}
.title {
font-size: 96px;
}
16
Laravel
</style>
</head>
<body>
<div class = "container">
</div>
</body>
</html>
Step 1
Step 2
17
Laravel
Now, the executed U RL should m atch with the appropriate m ethod in the route.php file.
I n the present case, it should m atch the m ethod and the root (‘/’) U RL. This will execute
the related function.
Step3
The function calls the tem plate file resources/views/welcome.blade.php. Next, the
function calls the view() function with argum ent ‘welcome’ without using
the blade.php. This will produce the HTML output as shown in the im age below:
Route Parameters
Som etim es in the web application, you m ay need to capture the param eters passed with
the U R L. For this, you should m odify the code in routes.php file.
You can capture the param eters in routes.php file in two ways as discussed here:
Required Parameters
These param eters are those which should be m andatorily captured for routing the web
application. For exam ple, it is im portant to capture the user’s identification number from
the U R L. This can be possible by defining route param eters as shown below:
Optional Parameters
Som etim es developers can produce param eters as optional and it is possib le with the
inclusion of ? after the param eter nam e in U R L. I t is im portant to keep the default value
m entioned as a param eter nam e. Look at the following example that shows how to define
an optional parameter:
18
Laravel
The example above checks if the value m atches to TutorialsPoint and accordingly routes
to the defined URL.
Named Routes
Nam ed routes allow a convenient way of creating routes. The chaining of routes can be
specified using nam e m ethod onto the route definition. The following code shows an
exam ple for creating nam ed routes with controller:
Route::get('user/profile', 'UserController@showProfile')->name('profile');
The user controller will call for the function showProfile with param eter as profile. The
param eters use name m ethod onto the route definition.
19
6. Laravel — Middleware Laravel
Laravel includes a m iddleware that verifies whether the user of the application is
authenticated or not. I f the user is authenticated, it redirects to the hom e page otherwise,
if not, it redirects to the login page.
R eplace the <middleware-name> with the nam e of your m iddleware. The m iddleware
that you create can be seen at app/Http/Middleware directory.
Example
O bserve the following example to understand the m iddleware m echanism:
Step 1
Let us now create AgeMiddleware . To create that, we need to execute the following
com m and:
Step 2
After successful execution of the com mand, you will receive the following output :
20
Laravel
Step 3
AgeMiddlware will be created at app/Http/Middlewa re. The newly created file will
have the following code already created for you.
<?php
namespace App\Http\Middleware;
use Closure;
class AgeMiddleware
{
public function handle($request, Closure $next)
{
return $next($request);
}
}
Registering Middleware
W e need to register each and every m iddleware before using it. There are two types of
Middleware in Laravel.
Global Middleware
R oute Middleware
The Global Middleware will run on every HTTP request of the application , whereas the
Route Middleware will be assigned to a specific route. The m iddleware can be registered
at app/Http/Kernel.php. This file contains two properties $middleware and
$routeMiddleware. $middleware property is used to register Global Middleware and
$routeMiddleware property is used to register route specific m iddleware.
To register the global m iddleware , list the class at the end of $m iddleware property.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
21
Laravel
To register the route specific m iddleware , add the key and value to $routeMiddleware
property.
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' =>
\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
Example
W e have created AgeMiddleware in the previous exam ple. W e can now register it in
route specific m iddleware property. The code for that registration is shown below.
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
22
Laravel
Middleware Parameters
W e can also pass param eters with the Middleware. For exam ple, if your application has
different roles like user, adm in, super adm in etc. and you want to authenticate the action
based on role , this can be achieved by passing param eters with m iddleware. The
m iddleware that we create contains the following function and we can pass our custom
argum ent after the $next argum ent.
Example
Step 1
Step 2
23
Laravel
Step 3
Add the following code in the handle m ethod of the newly created R oleMiddleware at
app/Http/Middleware /RoleMiddle ware.php.
<?php
namespace App\Http\Middleware;
use Closure;
class RoleMiddleware
{
public function handle($request, Closure $next, $role)
{
echo "Role: ".$role;
return $next($request);
}
}
Step 4
R egister the R oleMiddleware in app\Http\Kernel.php file. Add the line highlighted in
gray color in that file to register R oleMiddleware.
Step 5
24
Laravel
Step 6
After successful execution of the above step, you will receive the following output:
Step 7
app/Http/TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
}
}
Step 8
app/Http/routes.php
Route::get('role',[
'middleware' => 'Role:editor',
'uses' => 'TestController@index',
]);
Step 9
http://localhost:8000/role
Step 10
Terminable Middleware
Term inable m iddleware perform s som e task after the response has been sent to the
browser. This can be accomplished by creating a m iddleware with terminate m ethod in
the m iddleware. Term inable m iddleware should be registered with global m iddleware. The
term inate m ethod will receive two argum ents $request and $response. Term inate
m ethod can be created as shown in the following code.
Example
Step 1
26
Laravel
Step 2
Step 3
<?php
namespace App\Http\Middleware;
use Closure;
class TerminateMiddleware
{
public function handle($request, Closure $next)
{
echo "Executing statements of handle method of
TerminateMiddleware.";
return $next($request);
}
public function terminate($request, $response){
echo "<br>Executing statements of terminate method of
TerminateMiddleware.";
}
27
Laravel
Step 4
R egister the TerminateMiddleware in app\Http\Kernel.php file. Add the line
highlighted in gray color in that file to register Term inateMiddleware.
Step 5
28
Laravel
Step 6
After the successful execution of the U R L, you will receive the following output:
Step 7
app/Http/ABCController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
29
Laravel
Step 8
app/Http/routes.php
Route::get('terminate',[
'middleware' => 'terminate',
'uses' => 'ABCController@index',
]);
Step 9
http://localhost:8000/terminate
Step 10
30
7. Laravel- Namespaces Laravel
Nam espaces are used in various program ming languages to create a separate group of
variable, functions and classes. A program m ay contain various functions and this m ay
result in conflict with existing functions. Nam espaces play a key role in avoiding such
conflicts. This chapter gives you a detailed knowledge of nam espaces and their usage in
Laravel.
Declaration of namespace
Nam espaces can be defined as a class of elem ents in which each element has a unique
nam e to that associated class. I t m ay be shared with elem ents in other classes.
You can declare a nam espace as shown in the syntax given below:
use <namespace-name>;
Please note that the use keyword allows the developers to shorten the nam espace. The
default nam espace used in Laravel is app, however a user can change the nam espace to
m atch with a web application.
You can create a user defined nam espace by using artisan com m and as shown below:
O n giving the above com mand, you can observe the output as shown in the following
screenshot:
31
Laravel
The nam espace once created can include various functionalities which can be used in
controllers and various classes. The code created on the basis of nam espace in controller
and kernel with files nam ely app/console/kernel.php and app/Http/controller.php
are shown below:
Kernel.php
<?php
namespace Tutorialspoint\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
}
/**
* Register the Closure based commands for the application.
32
Laravel
*
* @return void
*/
protected function commands()
{
require base_path('routes/console.php');
}
}
Note that the functions nam ely schedule and com mands helps in scheduling m ethods for
Cron jobs and other functionalities.
Controller.php
<?php
namespace Tutorialspoint\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
33
Laravel
The controllers act as an interm ediary between m odels and views. For the nam espace
which we created called Tutorialspoint, they will be used in core file of controllers
controller.php. The nam espace is initialized properly with Http\Controllers.
The nam espace once created uses various other nam espaces like AuthorizesRequests,
DispatchesJobs and ValidatesRequests as m entioned in the above code.
Use Keyword
Nam espaces take place in the position of current class. As m entioned i n our exam ple we
have declared Tutorialspoint as our nam espace and it is located in the app folder. The
nam espace declared will be App\Tutorialpoint.
W henever you want to use that class, you should use the use keyword.
use Tutorialspoint\Http\Controllers\Controller;
34
8. Laravel – Controllers Laravel
I n the MVC fram ework, the letter ‘C’ stands for C ontroller. I t acts as a directing traffic
between Views and Models. I n this chapter, you will learn about C ontrollers in Laravel.
Creating a Controller
O pen the com mand prom pt or term inal based on the operating system you are using and
type the following com m and to create controller using the Artisan C LI (C ommand Line
I nterface).
R eplace the <controller-name> with the nam e of your controller. This will create a plain
constructor as we are passing the argum ent — plain. I f you don’t want to create a plain
constructor, you can sim ply ignore the argum ent. The created constructor can be seen at
app/Http/Controllers.
You will see that som e basic coding has already been done for you and you can add your
custom coding. The created controller can be called from routes.php by the following
syntax.
Route::get(‘base URI’,’controller@method’);
Example
Step 1: Execute the following com mand to create UserController.
35
Laravel
Step 2: After successful execution, you will receive the following output.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
Controller Middleware
W e have seen m iddleware before and it can be used with controller also. Middleware can
also be assigned to controller’s route or within your controller’s constructor. You can use
the m iddleware m ethod to assign m iddleware to the controller. The registered m iddleware
can also be restricted to certain m ethod of the controller.
36
Laravel
Route::get('profile', [
'middleware' => 'auth',
'uses' => 'UserController@showProfile'
]);
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
Here we are assigning auth m iddleware using the m iddleware m ethod in the
UserController constructor.
Example
Step 1: Add the following lines of code to the app/Http/routes.php file and save it.
routes.php
<?php
Route::get('/usercontroller/path',[
'middleware' => 'First',
'uses' => 'UserController@showPath'
37
Laravel
]);
Step 3: Add the following code in to the handle m ethod of the newly created
FirstMiddleware at app/Http/Middleware.
FirstMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class FirstMiddleware
{
public function handle($request, Closure $next)
{
echo '<br>First Middleware';
return $next($request);
}
}
Step 5: Add the following code in the handle m ethod of the newly created
SecondMiddleware at app/Http/Middlewa re.
38
Laravel
SecondMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
class SecondMiddleware
{
public function handle($request, Closure $next)
{
echo '<br>Second Middleware';
return $next($request);
}
}
Step 7: After successful execution of the U R L, you will receive the following output:
39
Laravel
app/Http/UserControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
Step 9: Now launch the PHP’s internal web server by executing the following com mand,
if you haven’t executed it yet.
http://localhost:8000/userco ntroller/path
40
Laravel
Step 11: The output will appear as shown in the following im age.
Example
Step 1: C reate a controller called MyController by executing the following com mand.
app/Http/Controllers/MyControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
42
Laravel
app/Http/routes.php
Route::resource('my','MyController');
Step 4: W e are now registering all the m ethods of MyController by registering a controller
with resource. Below is the table of actions handled by resource controller.
Implicit Controllers
I m plicit C ontrollers allow you to define a single route to handle every action in the
controller. You can define it in route.php file with Route:controlle r m ethod as shown
below.
R eplace the <class-name-of-the-controller> with the class nam e that you have given to
your controller.
The m ethod nam e of the controller should start with HTTP verb lik e get or post. I f you
start it with get, it will handle only get request and if it starts with post then it will handle
the post request. After the HTTP verb you can, you can give any nam e to the m ethod but
it should follow the title case version of the U R I.
43
Laravel
Example
Step 1: Execute the below com m and to create a controller. W e have kept the class nam e
ImplicitController. You can give any nam e of your choice to the class .
Step 2: After successful execution of step 1, you will receive the following output:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
/**
* Responds to requests to GET /test/show/1
*/
public function getShow($id)
{
echo 'show method';
}
/**
* Responds to requests to GET /test/admin -profile
*/
public function getAdminProfile()
{
echo 'admin profile method';
}
/**
* Responds to requests to POST /test/profile
*/
public function postProfile()
{
echo 'profile method';
}
}
Step 4: Add the following line to app/Http/routes.php file to route the requests to
specified controller.
app/Http/routes.php
Route::controller('test','ImplicitController');
45
Laravel
Constructor Injection
The Laravel service container is used to resolve all Laravel controllers. As a result, you are
able to type -hint any dependencies your controller m ay need in its constructor. The
dependencies will autom atically be resolved and injected into the controller instance.
Example
Step 1: Add the following code to app/Http/routes.php file.
app/Http/routes.php
class MyClass{
public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
http://localhost:8000/myclass
46
Laravel
Method Injection
I n addition to constructor injection, you m ay also type — hint dependencies on yo ur
controller's action m ethods.
Example
Step 1: Add the following code to app/Http/routes.php file.
app/Http/routes.php
class MyClass{
public $foo = 'bar';
}
Route::get('/myclass','ImplicitController@index');
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
47
Laravel
http://localhost:8000/myclass
48
9. Laravel — Request Laravel
Example
Step 1: Execute the below com m and to create a new controller called UriController.
Step 2: After successful execution of the U R L, you will receive the following output:
Step 3: After creating a controller, add the following code in that file.
app/Http/Controllers/UriController.php
<?php
namespace App\Http\Controllers;
49
Laravel
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
// Usage of is method
$pattern = $request->is('foo/*');
echo 'is Method: '.$pattern;
echo '<br>';
app/Http/route.php
Route::get('/foo/bar','UriController@index');
http://localhost:8000/foo/bar
Retrieving Input
The input values can be easily retrieved in Laravel. No m atter what m ethod was used get
or post, the Laravel m ethod will retrieve input values for both the m ethods the same way.
There are two ways we ca n retrieve the input values.
$name = $request->input('username');
$request->username
Example
O bserve the following example to understand m ore about R equests:
Step 1: C reate a R egistration form , where user can register him self and store the form
at resources/views/register.php
<html>
<head>
<title>Form Example</title>
</head>
<body>
<form action="/user/register" meth od="post">
<input type="hidden" name="_token" value="<?php echo csrf_token() ?>">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" /></td>
51
Laravel
</tr>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
52
Laravel
Step 3: After successful execution of the above step, you will receive the following
output:
app/Http/Controllers/Use rRegistration.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
53
Laravel
$username = $request->username;
echo 'Username: '.$username;
echo '<br>';
}
}
app/Http/routes.php
Route::get('/register',function(){
return view('register');
});
Route::post('/user/register',array('uses'=>'UserRegistration@postRegister'));
Step 6: Visit the following U R L and you will see the registration form as shown in the
below figure. Type the registration details and click Register and you will see on the second
page that we have retrieved and displayed the user registration details.
http://localhost:8000/register
Step 7: The output will look som ething like as shown in below the following im age s.
54
10. Laravel – Cookie Laravel
C ookies play an im portant role while dealing a user’s session on a web application. I n this
chapter, you will learn about working with cookies in Laravel based web applications.
Creating a Cookie
C ookie can be created by global cookie helper of Laravel. I t is an instance of
Symfony\Component\HttpFoundation\Cookie. The cookie can be attached to the
response using the withC ookie() m ethod. C reate a response instance of
Illuminate\Http\Response class to call the withC ookie() m ethod. C ookie generated by
the Laravel are encrypted and signed and it can’t be m odified or read by the client.
C ookie() m ethod will take 3 argum ents. First argum ent is the nam e of the cookie, second
argum ent is the value of the cookie and the third argum ent is the duration of the cookie
after which the cookie will get deleted autom atically.
C ookie can be set forever by using the forever m ethod as shown in the below code.
$response->withCookie(cookie()->forever('name', 'value'));
Retrieving a Cookie
O nce we set the cookie, we can retrieve the cookie by cookie() m ethod. This cookie()
m ethod will take only one argum ent which will be the nam e of the cooki e. The cookie
m ethod can be called by using the instance of Illuminate\Http\Request.
55
Laravel
Example
O bserve the following example to understand m ore about C ookies:
Step 1: Execute the below com m and to create a controller in which we will m anipulate
the cookie.
Step 2: After successful execution, you will receive the following output:
app/Http/Controllers/CookieControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Http\Requests;
use App\Http\Controllers\Controller;
56
Laravel
$minutes = 1;
$response = new Response('Hello World');
$response->withCookie(cookie('name', 'virat', $minutes));
return $response;
}
app/Http/routes.php
Route::get('/cookie/set','CookieController@setCookie');
Route::get('/cookie/get','CookieController@getCookie');
http://localhost:8000/cookie/set
57
Laravel
Step 6: The output will appear as shown below. The window appearing in the screenshot
is taken from fire fox but depending on your browser, cookie can also be checked from the
cookie option.
Step 7: Visit the following U R L to get the cookie from the above U RL.
http://localhost:8000/cookie/get
58
11. Laravel — Response Laravel
Basic Response
Laravel provides several different ways to return response. R esponse can be sent either
from route or from controller. The basic response that can be sent is sim ple string as
shown in the below sam ple code. This string will be autom atically converted to appropriate
HTTP response.
Example
Step 1: Add the following code to app/Http/routes.php file.
app/Http/routes.php
Route::get('/basic_response', function () {
return 'Hello World';
});
http://localhost:8000/basic_response
Attaching Headers
The response can be attached to headers using the header() m ethod. We can also attach
the series of headers as shown in the below sam ple code.
return response($content,$status)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
59
Laravel
Example
O bserve the following example to understand m ore about R esponse:
app/Http/routes.php
Route::get('/header',function(){
return response("Hello", 200)->header('Content-Type', 'text/html');
});
http://localhost:8000/header
Attaching Cookies
The withcookie() helper m ethod is used to attach cookies. The cookie generated with
this m ethod can be attached by calling withcookie() m ethod with response instance. By
default, all cookies generated by Laravel are encrypted and signed so that they can't be
m odified or read by the client.
Example
O bserve the following example to understand m ore about attaching cookies:
app/Http/routes.php
Route::get('/cookie',function(){
return response("Hello", 200)->header('Content-Type', 'text/html')-
>withcookie('name','Virat Gandhi');
});
http://localhost:8000/cookie
60
Laravel
JSON Response
JSO N response can be sent using the json m ethod. This m ethod will autom atically set the
C ontent-Type header to application/json. The json m ethod will autom atically convert
the array into appropriate json response.
Example
O bserve the following example to u nderstand m ore about JSON R esponse:
app/Http/routes.php
Route::get('json',function(){
return response()->json(['name' => 'Virat Gandhi', 'state' => 'Gujarat']);
});
http://localhost:8000/json
61
12. Laravel — Views Laravel
I n MVC fram ework, the letter V stands for Views. I t separates the application logic and
the presentation logic. Views are stored in resources/views directory. Generally, the
view contains the HTML which will be served by the application.
Example
O bserve the following example to understand m ore about Views:
<html>
<body>
<h1>Hello, World</h1>
</body>
</html>
Step 2: Add the following line in app/Http/routes.php file to set the route for the above
view.
app/Http/routes.php
Route::get('/test', function(){
return view('test');
});
http://localhost:8000/test
62
Laravel
Example
O bserve the following example to understand m o re about passing data to views:
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
Step 2: Add the following line in app/Http/routes.php file to set the route for the above
view.
app/Http/routes.php
Route::get('/test', function(){
return view('test',[‘name’=>’Virat Gandhi’] );
});
Step 3: The value of the key nam e will be passed to test.php file and $nam e will be
replaced by that value .
http://localhost:8000/test
63
Laravel
Example
O bserve the following example to understand m ore about sharing data with all views:
app/Http/routes.php
Route::get('/test', function(){
return view('test');
});
Route::get('/test2', function(){
return view('test2');
});
Step 2: C reate two view files — test.php and test2.php with the sam e code. These are
the two files which will share data. C opy the following code in both the files.
resources/views/test.php & resources/views/test2.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
64
Laravel
* @return void
*/
public function boot()
{
view()->share('name', 'Virat Gandhi');
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
http://localhost:8000/test
http://localhost:8000/test2
65
Laravel
13. Laravel - Blade Templates
Laravel 5.1 introduces the concept of using Blade, a tem plating engine to design a unique
layout. The layout thus designed can be used by other views, and includes a consistent
design and structure.
W hen com pared to other tem plating engines, Blade is unique in the following ways:
It does not restrict the developer from using plain PHP code in views.
The blade views thus designed, are compiled and cached until they are modified.
The com plete directory structure of Laravel is shown in the screenshot given here.
You can observe that all views are stored in the resources/views directory and the
default view for Laravel fram ework is welcome.blade.php.
Please note that other blade tem plates are also created sim ilarly.
66
Laravel
Step 1
Create a layout folder inside the resources/views folder. We are going to use this
folder to store all layouts together.
Create a file name master.blade.php which will have the following code associated
with it:
<!DOCTYPE html>
<html>
<head>
<title>DemoLaravel - @yield('title')</title>
</head>
<body>
@yield('content')
</body>
</html>
Step 2
I n this step, you should extend the layout. Extending a layout involves defining the child
elem ents. Laravel uses the Blade @extends directive for defining the child elem ents.
W hen you are extending a layout, please note the following points:
Views defined in the Blade Layout injects the container in a unique way.
@extends('layouts.app')
@section('title', 'Page Title')
@section('sidebar')
@parent
<p>This refers to the master sidebar.</p>
@endsection
67
Laravel
@section('content')
<p>This is my body content.</p>
@endsection
Step 3
To im plement the child elem ents in views , you should define the layout in the way it is
needed.
68
14. Laravel — Redirections Laravel
Nam ed route is used to give specific nam e to a route. The nam e can be assigned using
the as array key.
Example
O bserve the following example to understand m ore about R edirecting to nam ed routes:
<html>
<body>
<h1>Example of Redirecting to Named Routes</h1>
</body>
</html>
Step 2: I n routes.php, we have set up the route for test.php file. W e have renam ed it
to testing. W e have also set up another route redirect which will redirect the request to
the nam ed route testing.
app/Http/routes.php
http://localhost:8000/redirect
Step 5: After successful execution of the U R L, you will receive the following output:
return redirect()->action(‘NameOfController@methodName’,[parameters]);
Example
Step 1: Execute the following com mand to create a controller called RedirectController.
Step 2: After successful execution, you will receive the following output:
70
Laravel
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
app/Http/routes.php
Route::get('rr','RedirectController@index');
Route::get('/redirectcontroller',function(){
return redirect()->action('RedirectController@index');
});
http://localhost:8000/redirectcontroller
71
15. Laravel — Working with Database Laravel
Laravel has made processing with database very easy. Laravel currently supports following
4 databases:
MySQ L
Postgres
SQ Lite
SQ L Server
The query to the database can be fired using raw SQ L, the fluent query builder, and the
Eloquent ORM. To understand the all CRUD (Create, Read, U pdate, Delete) operations with
Laravel, we will use sim ple student m anagement system.
Connecting to Database
C onfigure the database in config/database.php file and create the college database with
structure in MySQ L as shown in the following table .
Database: College
Table: student
W e will see how to add, delete, update and retrieve records from database using Laravel
in student table.
Insert Records
W e can insert the record using the DB facade with insert m ethod. The syntax of insert
m ethod is as shown in the following table .
72
Laravel
Example
Step 1: Execute the below com m and to create a controller called StudInsertController
Step 2: After successful execution, you will receive the following output:
app/Http/Controllers/StudInsertControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
resources/views/stud_create.php
<html>
<head><title>Student Management | Add</title></head>
<body>
<form action="/create" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='stud_name' /></td>
</tr>
<tr>
<td colspan='2'><input type='submit' value="Add student" /></td>
</tr>
</table>
</form>
</body>
</html>
app/Http/routes.php
Route::get('insert','StudInsertController@insertform');
Route::post('create','StudInsertController@insert');
74
Laravel
http://localhost:8000/insert
Retrieve Records
After configuring the database, we can retrieve the records using the DB facade with
select m ethod. The syntax of select m ethod is as shown in the following table.
Example
Step 1: Execute the below com m and to create a controller called StudViewController.
75
Laravel
Step 2: After the successful execution of step 1, you will receive the following output:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
76
Laravel
resources/views/ stud_view.blade.php
<html>
<head><title>View Student Records</title></head>
<body>
<table border=1>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
</tr>
@endforeach
</table>
</body>
</html>
Route::get('view-records','StudViewController@index');
http://localhost:8000/view-records
77
Laravel
Update Records
W e can update the records using the DB facade with update m ethod. The syntax of update
m ethod is as shown in the following table .
Example
O bserve the following example to understand m ore about updating records:
Step 1: Execute the below com m and to create a controller called StudViewController.
Step 2: After successful execution, you will receive the following output:
78
Laravel
app/Http/Controllers/StudUpdateController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
79
Laravel
resources/views/ stud_edit_view.blade.php
<html>
<head><title>View Student Records</title></head>
<body>
<table border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Edit</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href='edit/{{ $user->id }}'>Edit</a></td>
</tr>
@endforeach
</table>
</body>
</html>
resources/views/stud_update.php
<html>
<head><title>Student Management | Edit</title></head>
<body>
<form action="/edit/<?php echo $users[0] ->id; ?>" method="post">
<input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<table>
<tr>
<td>Name</td>
<td><input type='text' name='stud_name' value='<?php echo
$users[0]->name; ?>' /></td>
80
Laravel
</tr>
<tr>
<td colspan='2'><input type='submit' value="Update student" /></td>
</tr>
</table>
</form>
</body>
</html>
Route::get('edit-records','StudUpdateController@index');
Route::get('edit/{id}','StudUpdateController@show');
Route::post('edit/{id}','StudUpdateController@edit');
http://localhost:8000/edit-records
Step 9: C lick the edit link on any record and you will be redirected to a page where you
can edit that particular record.
Step 10: The output will appear as shown in the following im age.
81
Laravel
Step 11: After editing that record , you will see a prom pt as shown in the following im age.
Delete Records
W e can delete the record using the DB facade with the delete m ethod. The syntax of
delete m ethod is shown in the following table .
Example
Step 1: Execute the below com m and to create a controller called StudDeleteController.
Step 2: After successful execution, you will receive the following output:
82
Laravel
app/Http/Controllers/StudDeleteControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
resources/views/stud_delete_vie w.blade.php
<html>
<head><title>View Student Records</title></head>
<body>
<table border="1">
<tr>
83
Laravel
<td>ID</td>
<td>Name</td>
<td>Edit</td>
</tr>
@foreach ($users as $user)
<tr>
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td><a href='delete/{{ $user ->id }}'>Delete</a></td>
</tr>
@endforeach
</table>
</body>
</html>
Route::get('delete-records','StudDeleteController@index');
Route::get('delete/{id}','StudDeleteController@destroy');
Step 7: C lick on delete link to delete that record from database. You will be redirected to
a page where you will see a m essage as shown in the following im age.
84
Laravel
Step 8: C lick on the Click Here link and you will be redirected to a page where you will
see all the records except the deleted one.
85
16. Laravel — Errors and Logging Laravel
This chapter deals with errors and logging in Laravel projects and how to work on them .
Errors
A project while underway, is borne to have a few errors. Errors and exception handling is
already configured for you when you start a new Laravel project. Norm ally, in a local
environm ent we need to see errors for debugging purposes. We need to hide these errors
from users in production environm ent. This can be achieved with the variable
APP_DEBUG set in the environm ent file .env stored at the root of the application.
For local environm ent the value of APP_DEBUG should be true, but for production it
needs to be set to false to hide errors.
Note: After changing the APP_DEBUG variable, you should restart the Laravel server.
Logging
Logging is an im portant m echanism by which system can log errors that are generated. It
is useful to im prove the reliability of the system. Laravel supports different logging m odes
like single, daily, syslog, and errorlog m odes. You can set these modes in config/app.php
file.
Step 1: I n this step, you should create a custom log file in Laravel using the Log façade.
The façade can be declared by sim ply using the use keyword in controller. I t is shown as
follows:
<?php
use Log;
}
}
?>
Here, the function nam e FuncName will help in creating logs by sending param eter
Log::info within the body of function.
Step 2: I f there is a need to save this file separately, you should do it at this step. For
this, you can use a dem o function like useDailyFiles() just before the inclusion of log
line as shown here :
<?php
use Log;
}
}
?>
All the logs will be tracked in file debug.log. The errors noted in the logs will be useful for
development.
Step 3: I n this step, you deal with the logger in Laravel, which includes various types
apart from Log::info m entioned in the exam ple given.
87
Laravel
Log::emergency($error);
Log::alert($error);
Log::critical($error);
Log::error($error);
Log::warning($error);
Log::notice($error);
Log::info($error);
Log::debug($error);
The types of errors which can be included in the log files are : emergency, alert, critical,
error, warning, notice, info and debug.
Based on the logs created, the im provements of web application are considered.
88
17. Laravel – Forms Laravel
Laravel provides various in built tags to handle HTML form s easily and securely. All the
m ajor elem ents of HTML are generated using Laravel. To support this , we need to add
HTML package to Laravel using com poser.
Example 1
Step 1: Execute the following com mand to proceed with the sam e.
Step 2: This will add HTML package to Laravel as shown in the following im age.
89
Laravel
Step 3: Now, we need to add the package shown above to Laravel configuration file which
is stored at config/app.php. O pen this file and you will see a list of Laravel service
providers as shown in the following im age. Add HTML service provider as indicated in the
outlined box in the following im age.
90
Laravel
Step 4: Add aliases in the sam e file for HTML and Form . Notice the two lines indicated in
the outlined box in the following im age and add those two lines .
91
Laravel
Step 5: Now everything is setup. Let’s see how we can use various HTML elements using
Laravel tags.
Opening a Form
echo Form::text('username');
echo Form::password('password');
echo Form::file('image');
92
Laravel
Example 2
Step 1
resources/views/form.php
<html>
<body>
<?php
echo Form::open(array('url' => 'foo/bar'));
echo Form::text('username','Username');
echo '<br/>';
echo Form::text('email', 'example@gmail.com');
echo '<br/>';
echo Form::password('password');
echo '<br/>';
echo Form::checkbox('name', 'value');
echo '<br/>';
echo Form::radio('name', 'value');
echo '<br/>';
echo Form::file('image');
echo '<br/>';
echo Form::select('size', array('L' => 'Large', ' S' =>
'Small'));
echo '<br/>';
echo Form::submit('Click Me!');
echo Form::close();
93
Laravel
?>
</body>
</html>
Step 2
Add the following line in app/Http/routes.php to add a route for view form .php
app/Http/routes.php
Route::get('/form',function(){
return view('form');
});
Step 3
http://localhost:8000/form
Step 4
94
18. Laravel – Localization Laravel
<?php
return [
'welcome' => 'Welcome to the application'
];
Example
Step 1: C reate 3 files for languages — English, French, and German. Save English file
at resources/lang/en/lang.php
<?php
return [
'msg' => 'Laravel Internationalization example.'
];
?>
<?php
return [
'msg' => 'Exemple Laravel internationalisation.'
];
?>
<?php
return [
'msg' => 'Laravel Internationalisierung Beispiel.'
];
95
Laravel
?>
Step 5: After successful execution, you will receive the following output:
app/Http/Controllers/LocalizationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
{
public function index(Request $request,$locale){
//set’s application’s locale
app()->setLocale($locale);
app/Http/routes.php
Route::get('localization/{locale}','LocalizationController@index');
Step 8: Now, let us visit the different U R Ls to see all different languages. Execute the
below U R L to see output in English language.
http://localhost:8000/localization/en
http://localhost:8000/localization/fr
Step 11: The output will appear as shown in the following im age.
97
Laravel
http://localhost:8000/localization/de
Step 13: The output will appear as shown in the following im age.
98
19. Laravel — Session Laravel
Sessions are used to store inform ation about the user across the requests. Larave l
provides various drivers like file, cookie, apc, array, Memcached, Redis, and
database to handle session data. By default, file driver is used because it is lightweight.
Session can be configured in the file stored at config/session.php.
$value = $request->session()->get('key');
You can use all() m ethod to get all session data instead of get() m ethod.
$request->session()->put('key', 'value');
$request->session()->forget('key');
U se flush() m ethod instead of forget() m ethod to delete all session data. U se the pull()
m ethod to retrieve data from session and delete it afterwards. The pull() m ethod will also
take key as the argum ent. The difference between the forget() and the pull() m ethod
is that forget() m ethod will not return the value of the session and pull() m ethod will
return it and delete that value from session.
Example
Step 1: C reate a controller called SessionController by executing the following
com m and.
99
Laravel
Step 2: After successful execution, you will receive the following output:
app/Http/Controllers/SessionControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
100
Laravel
app/Http/routes.php
Route::get('session/get','SessionController@accessSessionData');
Route::get('session/set','SessionController@storeSessionData');
Route::get('session/remove','SessionController@deleteSessionData');
http://localhost:8000/session/set
http://localhost:8000/session/get
101
Laravel
http://localhost:8000/session/remove
102
20. Laravel – Validation Laravel
Validation is the m ost im portant aspect while designing an application. I t validates the
incom ing data. By default, base controller class uses a ValidatesRequests trait which
provides a convenient m ethod to validate incom ing HTTP requests with a variety of
powerful validation rules.
103
Laravel
Example
Step 1: C reate a controller called ValidationController by executing the following
com m and.
Step 2: After successful execution, you will receive the following output:
app/Http/Controllers/ValidationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
104
Laravel
resources/views/login.blade.php
<html>
<head>
<title>Login Form</title>
</head>
<body>
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
<?php
echo Form::open(array('url'=>'/validation'));
?>
<table border='1'>
<tr>
<td align='center' colspan='2'>Login</td>
</tr>
<tr>
105
Laravel
<td>Username</td>
<td><?php echo Form::text('username'); ?></td>
</tr>
<tr>
<td>Password</td>
<td><?php echo Form::password('password'); ?></td>
</tr>
<tr>
<td align='center' colspan='2'><?php echo
Form::submit('Login'); ?></td>
</tr>
</table>
<?php
echo Form::close();
?>
</body>
</html>
app/Http/routes.php
Route::get('/validation','ValidationController@showform');
Route::post('/validation','ValidationController@validateform');
http://localhost:8000/validation
Step 7: C lick the Login button without entering anything in the text field. The output will
be as shown in the following im age.
106
21. Laravel – File Uploading Laravel
U ploading Files in Laravel is very easy. All we need to do is to create a view file where a
user can select a file to be uploaded and a controller where uploaded files will be processed.
I n a view file , we need to generate a file input by adding the following line of code.
Form::file('file_name');
I n Form ::open(), we need to add ‘files’=>’true’ as shown below. This facilitates the form
to be uploaded in m ultiple parts.
Example
Step 1: C reate a view file called resources/views/uploadfile.php and copy the
following code in that file.
resources/views/uploadfile.php
<html>
<body>
<?php
echo Form::open(array('url' =>
'/uploadfile','files'=>'true'));
echo 'Select the file to upload.';
echo Form::file('image');
echo Form::submit('Upload File');
echo Form::close();
?>
</body>
</html>
Step 3: After successful execution, you will receive the following output:
107
Laravel
app/Http/Controllers/UploadFileController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
108
Laravel
app/Http/routes.php
Route::get('/uploadfile','UploadFileController@index');
Route::post('/uploadfile','UploadFileController@showUploadFile');
http://localhost:8000/uploadfile
109
Laravel
110
22. Laravel – Sending Email Laravel
Laravel uses free feature -rich library SwiftMailer to send em ails. U sing the library
function, we can easily send em ails without too m any hassles. The e -m ail tem plates are
loaded in the sam e way as views, which m eans you can use the Blade syntax and inject
data into your tem plates.
The following table shows the syntax and attributes of send function:
I n the third argum ent, the $callback closure received m essage instance and with that
instance we can also call the following functions and alter the m essage as shown below.
$message->attach('path/to/attachment.txt');
$message->embed('path/to/attachment.jpg');
Mail can be sent as HTML or text. You can indicate the type of m ail that you want to send
in the first argum ent by passing an array as shown below. The default type is HTML. If
you want to send plain text m ail then use the following syntax.
111
Laravel
I n this syntax, the first argum ent takes an array. U se text as the key name of the view
as value of the key.
Example
Step 1: W e will now send an em ail from Gm ail account and for that you need to configure
your Gm ail account in Laravel environment file — .env file. Enable 2-step verification in
your Gm ail account and create an application specific password followed by changing the
.env param eters as shown below.
.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your-gmail-username
MAIL_PASSWORD=your-application-specific-password
MAIL_ENCRYPTION=tls
Step 2: After changing the .env file execute the below two com m ands to clear the cache
and restart the Laravel server.
Step 3: C reate a controller called MailController by executing the following com mand.
112
Laravel
Step 4: After successful execution, you will receive the following output:
app/Http/Controllers/MailControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
use App\Http\Requests;
use App\Http\Controllers\Controller;
113
Laravel
resources/views/mail.blade.php
app/Http/routes.php
114
Laravel
Route::get('sendbasicemail','MailController@basic_email');
Route::get('sendhtmlemail','MailController@html_email');
Route::get('sendattachmen temail','MailController@attachment_email');
http://localhost:8000/sendbasicemail
Step 9: The output screen will look something like this. C heck your inbox to see the basic
em ail output.
http://localhost:8000/sendhtmlemail
Step 11: The output screen will look something like this. Check your inbox to see the htm l
em ail output.
Step 12: Visit the following U RL to test the HTML em ail with attachm ent.
http://localhost:8000/sendattachmentemail
Note: I n the MailController.php file the em ail address in the from m ethod should be the
em ail address from which you can send em ail address. Generally, it should be the em ail
address configured on your server.
115
23. Laravel – Ajax Laravel
Example
Step 1: C reate a view file called resources/views/message.php and copy the following
code in that file.
<html>
<head>
<title>Ajax Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script
>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token=<?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to
replace the message.</div>
116
Laravel
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
Step 2: C reate a controller called AjaxController by executing the following com mand.
Step 3: After successful execution, you will receive the following output:
app/Http/Controllers/AjaxControlle r.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
117
Laravel
app/Http/routes.php
Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController@index');
http://localhost:8000/ajax
Step 7: You will be redirected to a page where you will see a m essage as shown in the
following im age.
Step 8: The output will appear as shown in the following im age after clicking the button.
118
24. Laravel – Error Handling Laravel
Most web applications have specific m echanisms for error handling. Using these, they track
errors and exceptions, and log them to analyze the perform ance. I n this chapter, you will
read about error handling in Laravel applications.
Important Points
Before proceeding further to learn in detail about error handling in Laravel, please note
the following im portant points:
● W hen your Laravel application is set in debug m ode, detailed error m essages with
stack traces will be shown on every error that occurs within your web application.
● By default, debug mode is set to false and you can change it to true. This enables the
user to track all errors with stack traces.
119
Laravel
● The configuration of Laravel project includes the debug option which determ ines
how m uch inform ation about an error is to be displayed to the user. By default in
a web application, the option is set to the value defined in the environm ent
variables of the .env file.
o The value is set to true in a local development environm ent and is set to
false in a production environment.
Error Log
Logging the errors in a web application helps to track them and in planning a strategy for
rem oving them . The log inform ation can be configured in the web application in
config/app.php file. Please note the following points while dealing with Error Log in
Laravel:
● The logging parameters used for error tracking are single, daily, syslog and
errorlog.
● For exam ple, if you wish to log the error m essages in log files, you should set the
log value in your app configuration to daily as shown in the com m and below:
120
Laravel
● I f the daily log m ode is taken as the param eter, Laravel takes error log for a period
of 5 days , by default. If you
wish to change the m aximum num ber of log files , you
have to set the param eter of log_max_files in the configuration file to a desired
value.
Severity Levels
As Laravel uses m onolog PHP logging library, there are various param eters used for
analyzing severity levels. Various severity levels that are available are error, critical,
alert and emergency messages. You can set the severity level as shown in the command
below:
121
25. Laravel – Event Handling Laravel
Events provide a sim ple observer im plementation which allows a user to subscribe and
listen to various events triggered in the web application. All the event classes in Laravel
are stored in the app/Events folder and the listeners are stored in the app/Listeners
folder.
The artisan com mand for generating events and listeners in your web application is shown
below:
This com mand generates the events an d listeners to the respective folders as discussed
above.
Events and Listeners serve a great way to decouple a web application, since one event can
have m ultiple listeners which are independent of each other. The events folder created by
the artisan com mand includes the following two files: event.php and Som eEvent.php. They
are shown here:
Event.php
<?php
namespace App\Events;
abstract class Event
{
//
}
122
Laravel
As m entioned above, event.php includes the basic definition of class Event and calls for
nam espace App\Events. Please note that the user defined or custom events are created
in this file.
SomeEvent.php
<?php
namespace App\Events;
use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
/**
* Create a new event instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Get the channels the event should be broadcas t on.
*
* @return array
*/
123
Laravel
O bserve that this file uses serialization for broadcasting events in a web application and
that the necessary param eters are also initialized in this file.
For example, if we need to initialize order variable in the constructor for registering an
event, we can do it in the following way:
Listeners
Listeners handle all the activities m entioned in an event that is being registered. The
artisan com m and event:generate creates all the listeners in the app/listeners
directory. The Listeners folder includes a file EventListener.php which has all the
m ethods required for handling listeners.
EventListener.php
<?php
namespace App\Listeners;
use App\Events\SomeEvent;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class EventListener
{
/**
* Create the event listener.
*
* @return void
*/
public function __construct()
{
//
}
/**
124
Laravel
As m entioned in the code, it includes handle function for m anaging various events. We
can create various independent listeners that target a single event.
125
26. Laravel – Facades Laravel
Facades provide a static interface to classes that are available in the application's service
container. Laravel facades serve as static proxies to underlying classes in the service
container, providing the benefit of a terse, expressive syntax while m aintaining m ore
testability and flexibility than traditional static m ethods.
126
Laravel
Example
Step 1: C reate a service provider called TestFacadesServiceProvider by executing the
following com mand.
127
Laravel
Step 2: After successful execution, you will receive the following output:
App/Test/TestFacades.php
<?php
namespace App\Test;
class TestFacades{
public function testingFacades(){
echo "Testing the Facades in Laravel.";
}
}
?>
App/Test/Facades/TestFacades.php
<?php
namespace app\Test\Facades;
use Illuminate\Support\Facades\Facade;
<?php
namespace App\Providers;
use App;
use Illuminate\Support\ServiceProvider;
Step 6: Add a service provider in a file config/app.php as shown in the below figure.
129
Laravel
config/app.php
config/app.php
app/Http/routes.php
Route::get('/facadeex', function(){
return TestFacades::testingFacades();
});
http://localhost:8000/facadeex
Step 10: After visiting the U RL, you will receive the following output:
131
27. Laravel - Contracts Laravel
Laravel contracts are a set of interfaces with various functionalities and core services
provided by the fram ework.
Every contract defined includes corresponding im plementation of the fram ework. All the
Laravel contracts are available in the GitHu b repository as m entioned below:
https://github.com/illuminate/contracts
This repository provides a variety of contracts available in the Laravel fram ework which
can be downloaded and used accordingly.
Important Points
W hile working with Laravel contracts, please note the following im portant points:
Contracts are explicitly defined in the classes and you need not define the contracts in
constructors.
Example
C onsider the contract used for Authorization in Laravel which is m entioned below:
<?php
namespace Illuminate\Contracts\Auth\Access;
interface Authorizable
{
/**
* Determine if the entity has a given ability.
*
* @param string $ability
* @param array|mixed $arguments
* @return bool
*/
public function can($ability, $arguments = []);
}
132
Laravel
The contract uses a function can which includes a parameter nam ed ability and
arguments which uses the user identification in the form of an array.
interface <contract-name>
C ontracts are used like facades for creating robust, well -tested Laravel applications. There
are various practical differences with usage of contracts and facades.
<?php
namespace App\Orders;
class Repository
{
/**
* The cache instance.
*/
protected $cache;
/**
* Create a new repository instance.
*
* @param Cache $cache
* @return void
*/
public function __construct(Cache $cache)
{
$this->cache = $cache;
}
}
133
28. Laravel - CSRF Protection Laravel
C SR F refers to C ross Site Forgery attacks on web applications. C SRF attacks are the
unauthorized activities which the authenticated users of the system perform . As such,
m any web applications are prone to these attacks.
Laravel includes an in built C SR F plug-in, that generates tokens for each active user
session. These tokens verify that the operations or requests are sent by the concerned
authenticated user.
Implementation
The im plementation of C SRF protection in Laravel is discussed in deta il in this section. The
following points are notable before proceeding further on C SR F protection:
CSRF is implemented within HTML forms declared inside the web applications. You
have to include a hidden validated CSRF token in the form, so that the CSRF protection
middleware of Laravel can validate the request. The syntax is shown below:
You can conveniently build JavaScript driven applications using JavaScript HTTP
library, as this includes CSRF token to every outgoing request.
The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel
applications and includes meta tag which stores csrf-token with Axios HTTP library.
<form>
<label> Email </label>
<input type="text" name="email"/>
<br/>
<label> Message </label> <input type="text" name="message"/>
<input type=”submit” name=”submitButton” value=”submit”>
134
Laravel
</form>
The form shown above will accept any input inform ation from an authorized user. This
m ay m ake the web application prone to various attacks.
Please note that the subm it button includes functionality in the controller section. The
postContact function is used in controllers for that associated views. I t is shown below:
O bserve that the form does not include any C SR F tokens so the sensitive inform ation
shared as input parameters are prone to various attacks.
The output achieved will return JSO N with a token as given below:
{
"token": "ghfleifxDSUYEW9WE67877CXNVFJKL" ,
135
Laravel
"name": "TutorialsPoint",
"email": "contact@tutorialspoint.com"
}
136
29. Laravel- Authentication Laravel
This chapter explains you the authentication process in Laravel web applications.
Command
Laravel uses the following com m and to create form s and the associated controllers to
perform authentication:
This com mand helps in creating authentication scaffolding successfully, as shown in the
following screenshot:
137
Laravel
Controller
The controller which is used for the authentication process is HomeController.
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
return view('home');
}
}
As a result, the scaffold application generated creates the login page and the registration
page for perform ing authentication. They are as shown below:
138
Laravel
Login
Registration
C onsider the following lines of code for LoginController which includes all the functions
for authentication:
<?php
// Authentication mechanism
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller
139
Laravel
{
/**
* Handling authentication request
*
* @return Response
*/
public function authenticate()
{
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
140
30. Laravel- Authorization Laravel
I n the previous chapter, we have studied about authentication process in Laravel. This
chapter explains you the authorization process in Laravel.
I n authentication, the web application or a system verifies the user through defined
credentials. I f the cred entials m atch as per the records, they are authenticated, or else
they are not.
W hen we describe the term authorization, it solely describes the verification if the
authenticated users can access the resources that is defined for them . I n other words, it
verifies their rights and perm issions over the requested and defined resources. I f the
authenticated users, can access the resources as defined, it m eans that they are
authorized.
Thus, authentication involves checking the validity of the user credentials, and
authorization involves checking the rights and perm issions over the resources that an
authenticated user has.
Policies are declared within an array and are used within classes and m ethods which use
authorization m echanism.
The following lines of code explain you how to use Gates and Policies for authorizing a user
in a Laravel web application. Note that in this exam ple, the boot function is used for
authorizing the users.
141
Laravel
<?php
namespace App\Providers;
/**
* Register any application authentication / authorization services.
*
* @param \Illuminate\Contracts\Auth\Access\Gate $gate
* @return void
*/
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
//
}
}
142
31. Laravel- Artisan Console Laravel
Laravel fram ework provides three prim ary tools for interaction through com mand -line
nam ely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail.
Introduction to Artisan
Artisan is the com m and line interface frequently used in Laravel and it includes a set of
helpful com mands for developing a web application.
Example
Here is a list of few com m ands in Artisan along with their respective functionalities:
4. To view help about any command and view the available options and
arguments
143
Laravel
The following screenshot shows the output of the com m ands given above:
Writing Commands
I n addition to the com m ands listed in Artisan, a user can also create a custom com mand
which can be used in the web application. Please note that com m ands are store d in
app/console/commands directory.
The default com mand for creating user defined com mand is shown below:
144
Laravel
O nce you type the above given com m and, you can see the output as shown in the
screenshot given below:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
/**
* The console command description.
145
Laravel
*
* @var string
*/
protected $description = 'Command description';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//
}
}
This file includes the signature and description for the com m and that user defined. The
public function named handle executes the functionalities when the com mand is executed.
These com mands are registered in the file Kernel.php in the sam e directory .
You can also create the schedule of tasks for the user defined com mand as shown in the
following code:
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
146
Laravel
Note that the schedule of tasks for the given com mand is defined in the function nam ed
schedule, which includes a param eter for scheduling the tasks which takes hourly
param eter.
The com m ands are registered in the array of com m ands, which includes the path and
nam e of the com m ands.
O nce the com m and is registered, it is listed in Artisan com m ands. The values included in
the signature and description section will be displayed when you call for the help attribute
of the specified com mand.
Let us see how to view the attributes of our com mand DefaultCommand. You should use
the com m and as shown below:
147
32. Laravel- Encryption Laravel
Laravel uses AES-256 and AES-128 encrypter, which uses O pen SSL for encryption. All
the values included in Laravel are signed using the protocol Message Authentication
Code so that the underlying value cannot b e tam pered with once it is encrypted.
Configuration
The com mand used to generate the key in Laravel is shown below:
Please note that this com mand uses the PHP secure random bytes’ generator and you can
see the output as shown in the screenshot given below:
The com m and given above helps in generating the key which can be used in web
application. O bserve the screenshot shown below:
148
Laravel
Note:
The values for encryption are properly aligned in the config/app.php file, which includes
two param eters for encryption nam ely key and cipher. I f the value using this key is not
properly aligned, all the values encrypted in Laravel will be insecure.
Encryption Process
Encryption of a value can be done by using the encrypt helper in the controllers of Laravel
class. These values are encrypted using O penSSL and AES-256 cipher. All the encrypted
values are signed with Message Authentication code (MAC) to check for any m odifications
of the encrypted string.
The code shown below is m entioned in a controller and is used to store a secret or a
sensitive m essage.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
*/
public function storeSecret(Request $request, $id)
{
$user = User::findOrFail($id);
$user->fill([
'secret' => encrypt($request ->secret)
])->save();
}
}
Decryption Process
Decryption of the values is done with the decrypt helper. O bserve the following lines of
code:
use Illuminate\Contracts\Encryption\DecryptException;
Please note that if the process of decryption is not successful because of invalid MAC being
used, then an appropriate exception is thrown.
150
33. Laravel- Hashing Laravel
Hashing is the process of transform ing a string of characters into a shorter fixed value or
a key that represents the original string. Laravel uses the Hash facade which provides a
secure way for storing passwords in a hashed m anner.
Basic Usage
The following screenshot shows how to create a controller nam ed passwordController
which is used for storing and updating passwords:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller
/**
* Updating the password for the user.
*
* @param Request $request
* @return Response
*/
public function update(Request $request)
{
// Validate the new password length...
$request->user()->fill([
'password' => Hash::make($request->newPassword) // Hashing
passwords
])->save();
}
}
The hashed passwords are stored using make m ethod. This m ethod allows m anaging the
work factor of the bcrypt hashing algorithm , which is popularly used in Laravel.
if (Hash::check('plain-text', $hashedPassword)) {
// The passwords match...
}
Note that the check m ethod com pares the plain-text with the hashedPassword variable
and if the result is true, it returns a true value.
152
34. Laravel - Understanding Release Process Laravel
Every web application fram ework has its own version history and it is always being updated
and m aintained. Every latest version brings new functionality and functions which are
either changed or deprecated, so it is im portant that you know which version will be
suitable for your projects.
W hen it com es to Laravel, there are two active versions as given below:
153
Laravel
The following points are worth notable in the context of understanding the release
process of Laravel:
All the controllers, m iddleware and requests are grouped within a directory under
the app/Http folder.
A new folder nam ely Providers directory is replaced with the app/start files in
the previous versions of Laravel 4.x.
All the language files and views are m oved to the resources directory.
New artisan com mand route:cache is used for registration of new routes and is
included with the release of Laravel 5.1 and further versions.
Laravel supports HTTP middleware and also includes CSRF tokens and
authentication m odel.
All the authentication m odels are located under one directory nam ely
resources/views/auth. I t includes user registration, authentication and
password controllers.
154