UNIT-2 Introduction to Laravel, Artisan, Route and Controller
What is Laravel?
The need for frameworks
Of all the server-side programming languages, PHP undoubtedly has
the lowest entry barriers. It is almost always installed by default on
even the cheapest web hosts, and it is also extremely easy to set up on
any personal computer. For newcomers who have some experience
with authoring web pages in HTML and CSS, the concepts of
variables, inline conditions, and include statements are easy to grasp.
PHP also provides many commonly used functions that one might
need when developing a dynamic website. All of this contributes to
what some refer to as the immediacy of PHP. However, this instant
gratification comes at a cost. It gives a false sense of productivity to
beginners, who almost inevitably end up with convoluted spaghetti
code as they add more features and functionality to their site. This is
mainly because PHP, out of the box, does not do much to encourage
the separation of concerns.
The limitations of homemade tools
If you already have a few PHP projects under your belt, but have not
used a web application framework before, then you will probably
have amassed a personal collection of commonly used functions and
classes that you can use on new projects. These homegrown utilities
might help you with common tasks, such as sanitizing data,
authenticating users, and including pages dynamically. You might
also have a predefined directory structure where these classes and the
rest of your application code reside. However, all of this will exist in
complete isolation; you will be solely responsible for the
maintenance, inclusion of new features, and documentation. Fora lone
developer or an agency with ever-changing staff, this can be a tedious
and time-consuming task, not to mention that if you were to
collaborate with other developers on the project, they would first have
to get acquainted with the way in which you build applications.
Laravel to the rescue
This is exactly where a web application framework such as Laravel
comes to the rescue. Laravel reuses and assembles existing
components to provide you with a cohesive layer up- on which you
can build your web applications in a more structured and pragmatic
way. Drawing inspiration from popular frameworks written not just in
1
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
PHP but other programming languages too, Laravel offers a robust set
of tools and an application architecture that incorporates many of the
best features of frameworks like Code Igniter, Yii, ASP.NET MVC,
Ruby on Rails, Sinatra, and others. Most of these frameworks use the
Model-View- Controller (MVC) paradigm or design pattern. If you
have used one of the aforementioned tools or the MVC pattern, then
you will find it quite easy to get started with Laravel 5.
Features
• Modularity: Laravel was built on top of over 20 different libraries
and is itself split into individual modules. Tightly integrated with
Composer dependency manager, these components can be updated
with ease.
• Testability: Built from the ground up to ease testing, Laravel ships
with several helpers that let you visit routes from your tests, crawl the
resulting HTML, ensure that methods are called on certain classes,
and even impersonate authenticated users in order to make sure the
right code is run at the right time.
• Routing: Laravel gives you a lot of flexibility when you define the
routes of your application. For example, you could manually bind a
simple anonymous function to a route with an HTTP and HTTPS
verb, such as GET, POST, PUT, or DELETE. This feature is inspired
by micro- frameworks, such as Sinatra(Ruby) and Silex (PHP).
•Configuration management: More often than not, your application
will be running in different environments, which means that the
database ore-mail server credential's settings or the displaying of error
messages will be different when your app is running on a local devel-
opment server to when it is running on a production server. Laravel
has a consistent approach to handle configuration settings, and
different settings can be applied indifferent environments via the use
of an. env file, containing settings unique for that environment.
• Query builder and ORM: Laravel ships with a fluent query builder,
which lets you issue database queries with a PHP syntax, where you
simply chain methods instead of writing SQL. In addition to this, it
provides you with an Object Relational Mapper (ORM) and
2
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
Active Record implementation, called Eloquent, which is similar to
what you will find in Ruby on Rails, to help you define
interconnected models. Both the query builder and the ORM are
compatible with different databases, such as PostgreSQL, SQLite,
MySQL, and SQL Server.
• Schema builder, migrations, and seeding: Also inspired by Rails,
these features allow you to define your database schema in PHP code
and keep track of any changes with the help of database migrations. A
migration is a simple way of describing a schema change and how to
revert to it. Seeding allows you to populate the selected tables of your
database, for example, after running a migration.
• Template engine: Partly inspired by the Razor template language in
ASP.NET MVC, Laravel ships with Blade, a lightweight template
language with which you can create hierarchical layouts with
predefined blocks in which dynamic content is injected.
• E-mailing: With its Mail class, which wraps the popular
SwiftMailerlibrary, Laravel makes it very easy to send an e-mail,
even with rich content and attachments from your application. Laravel
also comes with drivers for popular e-mail sending services such as
SendGrid, Mailgun, and Mandrill.
• Authentication: Since user authentication is such a common feature
in web applications, out of the box Laravel comes with a default
implementation to register, authenticate, and even send password
reminders to users.
•Redis: This is an in-memory key-value store that has a reputation for
being extremely fast. If you give Laravel a Redis instance that it can
connect to, it can use it as a session and general-purpose cache, and
also give you the possibility to interact with it directly.
• Queues: Laravel integrates with several queue services, such as
Amazon SQS, Beanstalkd, and IronMQ, to allow you to delay
resource-intensive tasks, such as the e-mailing of a large number of
users, and run them in the background, rather than keep the user
waiting for the task to complete.
3
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
• Event and command bus: Although not new in version 5, Laravel
has brought a command bus to the forefront in which it's easy to
dispatch events (a class that represents something that's happened in
your application), handle commands (another class that represents
some- thing that should happen in your application), and act upon
these at different points in your application's lifecycle.
MVC architecture
• Models: Models represent resources in your application. More often
than not, they correspond to records in a data store, most commonly a
database table. In this respect, you can think of models as representing
entities in your application, be that a user, a news article, or an event,
among others. In Laravel, models are classes that usually extend
Eloquent's base Model class and are named in CamelCase (that is,
News Article). This will correspond to a database table with the same
name, but in snake_case and plural (that is, news_articles). By
default, Eloquent also expects a primary key name did, and will also
look for and automatically update the created at and updated at
columns. Models can also describe the relationships they have with
other model for example, a News Article model might be associated
with a User model, as a User model might be able to author a News
Article model.
4
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
•Controllers or routes: Controllers, at their simplest, take a request,
do something, and then send an appropriate response. Controllers are
where the actual processing of data goes, whether that is retrieving
data from a database, or handling a form submission, and saving data
back to a database. Although you are not forced to adhere to any rules
when it comes to creating controller classes in Laravel, it does offer
you two sane approaches: REST- ful controllers and resource
controllers. A RESTful controller allows you to define your own
actions and what HTTP methods they should respond to. Resource
controllers are based around an entity and allow you to perform
common operations on that entity, based on the HTTP method used.
• Views or Templates: Views are responsible for displaying the
response returned from a controller in a suitable format, usually as an
HTML webpage. They can be conveniently built by using the Blade
template language or by simply using standard PHP. The file
extension of the view, either.blade.php or simply. php, determines
whether or not Laravel treats your view as a Blade template or not.
Using Laravel Installer
Laravel utilizes Composer to manage its dependencies. So, before
using Laravel, make sure you have Composer installed on your
machine.
[composer global require "laravel/installer"]
Make sure to place the ~/. composer/vendor/bin directory (or the
equivalent directory for your OS) in your PATH so the Laravel
executable can be located by your system.
Once installed, the Laravel new command will create a fresh Laravel
installation in the directory you specify. For instance, Laravel new
blog will create a directory named blog containing a fresh Laravel
installation with all of Laravel’s dependencies already installed. This
method of installation is much faster than installing via Composer:
5
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
Using Composer
Strongly inspired by popular dependency managers in other
languages, such as Ruby's Bundler or Node.js's Node Package
Manager (npm), Composer brings these features to PHP and has
quickly become the de-facto dependency manager in PHP.
How does Composer work?
A few years ago, you may have used PHP Extension and
Application Repository(PEAR) to download libraries. PEAR differs
from Composer, in that PEAR would install packages on a system-
level basis, whereas a dependency manager, such as Composer,
installs them on a project-level basis. With PEAR, you could only
have one version of a package installed on a system. Composer allows
you to use different versions of the same package in different ap-
plications, even if they reside on the same system.
Windows
This is the easiest way to get Composer set up on your
machine. Download and run Composer-Setup.exe. It will install the
latest Composer version and set up your PATH so that you can call
composer from any directory in your command line.
Finding and installing new packages
Via Composer Create-Project Alternatively, you may also install Laravel by
issuing the Composer create-project command in your terminal:
Environment configuration
All of the configuration files for the Laravel framework are stored in
the Config directory. Each option is documented, so feel free to look
through the files and get familiar with the options available to you.
It is often helpful to have different configuration values based on the
environment the application is running in. For example, you may wish
to use a different cache driver locally than you do on your production
server. It's easy using environment-based configuration.
To make this a cinch, Laravel utilizes the DotEnv PHP library by
Vance Lucas. In a fresh Laravel installation, the root directory of your
application will contain a .env.example file. If you install Laravel via
Composer, this file will automatically be renamed to .env. Otherwise,
6
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
you should rename the file manually.
All of the variables listed in this file will be loaded into the $_ENV
PHP super-global when your application receives a request. However,
you may use the env helper to retrieve values from these variables in
your configuration files. In fact, if you review the Laravel configura-
tion files, you will notice several of the options already using this
helper:
'debug' => env('APP_DEBUG', false),
The second value passed to the env function is the "default value".
This value will be used if no environment variable exists for the given
key.
Your .env file should not be committed to your application's source
control, since each de- veloper / server using your application could
require a different environment configuration.
If you are developing with a team, you may wish to continue
including a .env.example file with your application. By putting place-
holder values in the example configuration file, other developers on
your team can clearly see which environment variables are needed to
run your application.
Protecting Sensitive Configuration
For "real" applications, it is advisable to keep all of your sensitive
configuration out of your configuration files. Things such as database
passwords, Stripe API keys, and encryption keys should be kept out
of your configuration files whenever possible. So, where should we
place them? Thankfully, Laravel provides a very simple solution to
protecting these types of con- figuration items using "dot" files.
First, configure your application to recognize your
machine as being in the local environment. Next, create a
.env.local.php file within the root of your project,
which is usually the same directory that contains your
composer.json file. The .env.local.php should return an array of key-
value pairs, much like a typical Laravel con- figuration file:
7
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
<?php
return array(
'TEST_STRIPE_KEY' => 'super-secret-sauce',
);
All of the key-value pairs returned by this file will
automatically be available via the $_ENV and $_SERVER PHP
"superglobals". You may now reference these globals from within
your configuration files:
'key' => $_ENV['TEST_STRIPE_KEY']
Be sure to add the .env.local.php file to your .gitignore file. This will
allow other developers on your team to create their own local
environment configuration, as well as hide your sensitive
configuration items from source control.
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.
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 up- dating or when you are
performing maintenance. A call to the App::down method is already
present in your app/start/global.php file. The response from this
method will be sent to users when your application is in maintenance
mode. To enable maintenance mode, simply execute the down Artisan
command:
php artisan down
To disable maintenance mode, use the up command:
php artisan up
8
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
To show a custom view when your application is in maintenance
mode, you may add some- thing like the following to your
application's app/start/global.php file:
App::down(function()
{
return Response::view('maintenance', array(), 503);
});
If the Closure passed to the down method returns NULL,
maintenance mode will be ignored for that request.
The Root Directory
The root directory of a fresh Laravel installation contains a variety of
directories:
The app directory, as you might expect, contains the core code of
your application. We'll explore this directory in more detail soon.
The bootstrap directory contains a few files that bootstrap the
framework and configure auto loading, as well as a cache directory
that contains a few frameworks generated files for bootstrap
performance optimization.
The Config directory, as the name implies, contains all of your
application's configuration files.
The database directory contains your database migration and seeds.
If you wish, you may also use this directory to hold an SQLite
database.
The public directory contains the front controller and your assets
(images, JavaScript, CSS, etc.).
The resources directory contains your views, raw assets (LESS,
SASS, Coffee Script), and localization files.
The storage directory contains compiled Blade templates, file based
sessions, file caches, and other files generated by the framework. This
directory is segregated into app, frame- work, and logs directories.
The app directory may be used to store any files utilized by your
application. The framework directory is used to store framework
generated files and caches. Finally, the logs directory contains your
application's log files.
9
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
The tests directory contains your automated tests. An example
PHPUnit is provided out of the box.
The vendor directory contains your Composer dependencies.
The App Directory
The "meat" of your application lives in the app directory. By default,
this directory is namespaced under App and is autoloaded by
Composer using the PSR-4 autoloading stand- ard.
The app directory ships with a variety of additional directories such
as Console, Http, and Providers. Think of the Console and Http
directories as providing an API into the "core" of your application.
The HTTP protocol and CLI are both mechanisms to interact with
your ap- plication, but do not actually contain application logic. In
other words, they are simply two ways of issuing commands to your
application. The Console directory contains all of your Artisan
commands, while the Http directory contains your controllers,
middleware, and re- quests.
The Events directory, as you might expect, houses event classes.
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.
The Exceptions directory contains your application's exception
handler and is also a good place to stick any exceptions thrown by
your application.
The Jobs directory, of course, houses the queueable jobs for your
application. Jobs may be queued by your application or run
synchronously within the current request lifecycle.
The Listeners 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.
The Policies directory contains the authorization policy classes for
your application. Policies are used to determine if a user can perform
a given action against a resource. For more in- formation check out
the authorization documentation.
10
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
Note: Many of the classes in the app directory can be generated by
Artisan via commands. To review the available commands, run the
php artisan list make command in your terminal.
Artisan Command Line Tool
Introduction
Artisan is the name of the command-line interface included with
Laravel. It provides a number of helpful commands for your use while
developing your application. It is driven by the powerful Symfony
Console component.
Usage
Listing All Available Commands
To view a list of all available Artisan commands, you may use the list
command:
php artisan list
Viewing The Help Screen For A Command
Every command also includes a "help" screen which displays and
describes the command's available arguments and options. To view a
help screen, simply precede the name of the command with help:
php artisan help migrate
Basic Routing
The most basic Laravel routes accept a URI and a closure, providing a
very simple and ex- pressive method of defining routes and behavior
without complicated routing configuration files:
use Illuminate\Support\Facades\Route;
Route::get('/greeting', function () {
return 'Hello World';
});
Route Parameters
Required Parameters
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
11
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
URL. You may do so by defining route parame- ters:
Route::get('/user/{id}', function ($id) {
return 'User '.$id;
});
You may define as many route parameters as required by your route:
Route::get('/posts/{post}/comments/{comment}', function ($postId, $commentId) {
//
});
Route parameters are always encased within {} braces and should
consist of alphabetic characters. Underscores (_) are also acceptable
within route parameter names. Route pa- rameters are injected into
route callbacks / controllers based on their order - the names of the
route callback / controller arguments do not matter.
Parameters & Dependency Injection
If your route has dependencies that you would like the Laravel
service container to automatically inject into your route's callback,
you should list your route parameters after your dependencies:
use Illuminate\Http\Request;
Route::get('/user/{id}', function (Request $request, $id) {
return 'User '.$id;
});
Named Routes
Named routes allow the convenient generation of URLs or redirects
for specific routes. You may specify a name for a route by chaining
the name method onto the route definition:
Route::get('/user/profile', function () {
//
})->name('profile');
You may also specify route names for controller actions:
Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');
12
UNIT-2 Introduction to Laravel, Artisan, Route and Controller
Note:
Route names should always be unique.
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 generated URL in their correct
positions:
Route::get('/user/{id}/profile', function ($id) {
//
})->name('profile');
$url = route('profile', ['id' => 1]);
If you pass additional parameters in the array, those key / value pairs
will automatically be added to the generated URL's query string:
Route::get('/user/{id}/profile', function ($id) {
//
})->name('profile');
$url = route('profile', ['id' => 1, 'photos' => 'yes']);
// /user/1/profile?photos=yes
13