This tutorial will guide the developers and students who want to find out the way to develop website site using Laravel. This tutorial is especially meant for all those developers who haven’t any prior experience of using Laravel.

Laravel is a powerful MVC PHP framework, designed for developers who need an easy and stylish toolkit to make full-featured web applications. Laravel was created by Taylor Otwell. This is a quick tutorial that explains the fundamentals of Laravel framework.

Before you begin proceeding with this tutorial, we assume that you simply are conversant in HTML, Core PHP, and Advance PHP. If you are new to any of these concepts, we suggest you pick tutorials based on these concepts first, to gain a better understanding of Laravel.

Laravel offers an upscale set of functionalities which includes the essential features of PHP frameworks like CodeIgniter, Yii, and other programming languages like Ruby on Rails. Laravel features a very rich set of features that can boost the speed of web development.

If you’re conversant in Core PHP and Advanced PHP, Laravel will make your task easier. It saves a lot of time if you are planning to develop a website from scratch. Moreover, an internet site inbuilt Laravel is secure and prevents several web attacks.

Advantages of Laravel
Laravel offers you the subsequent advantages, once you are designing an internet application supported it −

  • The web application becomes more scalable, due to the Laravel framework.
  • Considerable time is saved in designing the online application since Laravel reuses the components from other frameworks in developing web applications.
  • It includes namespaces and interfaces, thus helps to organize and manage resources.

Composer
Composer is a tool that includes all the dependencies and libraries. It allows a user to make a project with reference to the mentioned framework (for example, those utilized in Laravel installation). Third-party libraries are often installed easily with the help of composer.

All the dependencies are noted in composer.json file which is placed in the source folder.

Artisan
The command-line interface utilized in Laravel is named Artisan. It includes a set of commands which assists in building a web application. These commands are incorporated from the Symphony framework, leading to add-on features in Laravel 5.1 (latest version of Laravel).

Features of Laravel
Laravel offers the subsequent key features which make it a perfect choice for designing web applications −

Modularity
Laravel provides 20 inbuilt libraries and modules which help in the enhancement of the appliance. Every module is integrated with Composer dependency manager which eases updates.

Testability
Laravel includes features and helpers which helps in testing through various test cases. This feature helps in maintaining the code as per the requirements.

Routing
Laravel provides a versatile approach to the user to define routes within the web application. Routing helps to scale the application in a better way and increases its performance.

Configuration Management
A web application designed in Laravel is going to be running on different environments, which suggests that there’ll be a continuous change in its configuration. Laravel provides a uniform approach to handle the configuration in an efficient way.

Query Builder and ORM
Laravel incorporates a question builder which helps in querying databases using various simple chain methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called Eloquent.

Schema Builder
Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track of changes with respect to database migrations.

Template Engine
Laravel uses the Blade template engine, a light-weight template language wont to design hierarchical blocks and layouts with predefined blocks that include dynamic content.

E-mail
Laravel includes a mail class that helps in sending mail with rich content and attachments from the online application.

Authentication
User authentication may be a common 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. Redis interacts with the session directly.

Queues
Laravel includes queue services like emailing a sizable amount of users or a specified Cron job. These queues help in completing tasks in an easier manner without waiting for the previous task to be completed.

Event and Command Bus
Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a simple way. The commands in Laravel act as per the application’s lifecycle.

For managing dependencies, Laravel uses composer. Make sure you’ve got a Composer installed on your system before you install Laravel. In this chapter, you’ll see the installation process of Laravel.

You will have to follow the steps given below for installing Laravel onto your system −

Step 1 − Visit the following URL and download composer to install it on your system.

https://getcomposer.org/download/

Step 2 − After the Composer is installed, check the installation by typing the Composer command in the command prompt as shown in the following screenshot.

Step 3− Create a new directory anywhere in your system for your new Laravel project. After that, move to path where you have created the new directory and type the following command there to install Laravel.
composer create-project laravel/laravel –-prefer-dist

Now, we will focus on the installation of version 5.7. In Laravel version 5.7, you can install the complete framework by typing the following command −

composer create-project laravel/laravel test dev-develop

The output of the command is as shown below −

The Laravel framework can be directly installed with develop branch which includes the latest framework.

Step 4 − The above command will install Laravel in the current directory. Start the Laravel service by executing the following command.

php artisan serve

Step 5 − After executing the above command, you will see a screen as shown below −

Step 6

− Copy the URL underlined in gray in the above screenshot and open that URL in the browser. If you see the following screen, it implies Laravel has been installed successfully.

The application structure in Laravel is essentially the structure of folders, sub-folders and files included during a project. Once we create a project in Laravel, we get an summary of the appliance structure as shown within the image here.

The snapshot shown here refers to the basis folder of Laravel namely laravel-project. It includes various sub-folders and files. The analysis of folders and files, along with their functional aspects is given below −

App
It is the application folder and includes the entire source code of the project. It contains events, exceptions, and middleware declaration. The app folder comprises various sub-folders as explained below −

Console
Console includes the artisan commands necessary for Laravel. It includes a directory named Commands, where all the commands are declared with the appropriate signature. The file Kernal.php calls the commands declared in Inspire.php.

If we’d like to call a selected command in Laravel, then we should always make appropriate changes during this directory.

Events

This folder includes all the events for the project.

Events are wont to trigger activities, raise errors or necessary validations, and supply greater flexibility. Laravel keeps all the events under one directory. The default file included is event.php where all the essential events are declared.

Exceptions
This folder contains all the methods needed to handle exceptions. It also contains the file handle.php that handles all the exceptions.

Http
The Http folder has sub-folders for controllers, middleware, and application requests. As Laravel follows the MVC design pattern, this folder includes model, controllers, and views defined for the precise directories.

The Middleware sub-folder includes the middleware mechanism, comprising the filter mechanism and communication between response and request.

The Requests sub-folder includes all the requests of the application.

Jobs
The Jobs directory maintains the activities queued for Laravel application. The base class is shared among all the Jobs and provides a central location to place them under one roof.

Listeners
Listeners are event-dependent and they include methods that are used to handle events and exceptions. For example, the login event declared includes a LoginListener event.

Policies
Policies are the PHP classes which include the authorization logic. Laravel includes a feature to make all authorization logic within policy classes inside this sub-folder.

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. It contains a sub-folder namely cache, which includes all the files associated with caching a web application. You can also find the file app.php, which initializes the scripts necessary for bootstrap.

Config
The config folder includes various configurations and associated parameters required for the smooth functioning of a Laravel application. Various files included within the config folder are as shown in the image here. The filenames work as per the functionality associated with them.

Database
As the name suggests, this directory includes various parameters for database functionalities. It includes three sub-directories as given below −

Seeds − This contains the classes used for unit testing database.

Migrations − This folder helps in queries for migrating the database used in the web application.

Factories − This folder is used to generate large number of data records.

Public
It is the root folder which helps in initializing the Laravel application. It includes the following files and folders −

.htaccess − This file gives the server configuration.

javascript and css − These files are considered as assets.

index.php − This file is required for the initialization of a web application.

Resources
Resources 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 SCSS, that are required for styling the web application.

lang − This folder includes configuration for localization or internalization.

views − Views are the HTML files or templates which interact with end users and play a primary role in MVC architecture.

Storage
This is the folder that stores all the logs and necessary files that 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 − It 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 naming convention for naming test case classes is camel_case and follows the convention as per the functionality of the class.

Vendor
Laravel is totally supported Composer dependencies, for instance, to put in Laravel setup or to incorporate third-party libraries, etc. The Vendor folder includes all the composer dependencies.

In addition to the above-mentioned files, Laravel also includes another files which play a primary role in various functionalities like GitHub configuration, packages, and third-party libraries.

The files included in the application structure are shown below −

In the previous chapter, we’ve seen that the essential configuration files of Laravel are included within the config directory. In this chapter, allow us to discuss the categories included within the configuration.

Environment Configuration
Environment variables are those which provide a list of web services to your web application. All the environment variables are declared in the .env file which includes the parameters required for initializing the configuration.

By default, the .env file includes following parameters −

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

Important Points
While 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.

Retrieval of Environment Variables
All the environment variables declared in the .env file can be accessed by env-helper functions which will call the respective parameter. These variables are also listed into $_ENV global variable whenever the application receives a request from the user end. You can access the environment variable as shown below −

'env' => env('APP_ENV', 'production'),

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 parameter.

Accessing Configuration Values
You can easily access the configuration values anywhere in the application using the global config helper function. In case if the configuration values are not initialized, default values are returned.

For example, to set the default time zone, the following code is used −

config(['app.timezone' => 'Asia/Kolkata']);

Caching of Configuration
To increase the performance and to boost the web application, it is important to cache all the configuration values. The command for caching the configuration values is −

config:cache

The following screenshot shows caching in a systematic approach −

Maintenance Mode
Sometimes you may need to update some configuration values or perform maintenance on your website. In such cases, keeping it in maintenance mode, makes it easier for you. Such web applications which are kept in maintenance mode, throw an exception namely MaintenanceModeException with a status code of 503.

You can enable the maintenance mode on your Laravel web application using the following command −

php artisan down

The following screenshot shows how the web application looks when it is down −

Once you finish working on updates and other maintenance, you can disable the maintenance mode on your web application using the following command −

php artisan up

Now, you can find that the website shows the output with proper functioning and depicting that the maintenance mode is now removed as shown below −

In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel.

Routing in Laravel includes the following categories −

  • 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 URIs it should respond to and the associated controller will give it a particular call. The sample route for the welcome page can be seen as shown in the screenshot given below −

Route::get ('/', function () {
return view('welcome');});

Example

Observe the following example to understand more about Routing −

app/Http/routes.php


Route::get('/', function () {
return view('welcome');
});

resources/view/welcome.blade.php

 

 

 

Laravel 5.1

The routing mechanism is shown in the image given below −

Let us now understand the steps involved in routing mechanism in detail −

Step 1 − Initially, we should execute the root URL of the application.

Step 2 − Now, the executed URL should match with the appropriate method in the route.php file. In the present case, it should match the method and the root (‘/’) URL. This will execute the related function.

Step 3 − The function calls the template file resources/views/welcome.blade.php. Next, the function calls the view() function with argument ‘welcome’ without using the blade.php.

This will produce the HTML output as shown in the image below −

Route Parameters
Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in routes.php file.

You can capture the parameters in routes.php file in two ways as discussed here −

Required Parameters
These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below −

Route::get('ID/{id}',function($id) {
echo 'ID: '.$id;
});

Optional Parameters
Sometimes developers can produce parameters as optional and it is possible with the inclusion of ? after the parameter name in URL. It is important to keep the default value mentioned as a parameter name. Look at the following example that shows how to define an optional parameter −

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

The example above checks if the value matches to 3iLogics and accordingly routes to the defined URL.

Named Routes
Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition. The following code shows an example for creating named routes with controller −

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

The user controller will call for the function show profile with parameter as profile. The parameters use name method onto the route definition.

Middleware acts as a bridge between an invitation and a response. It is a type of filtering mechanism. This chapter explains the middleware mechanism in Laravel.

Laravel includes a middleware that verifies whether the user of the appliance is authenticated or not. If the user is authenticated, it redirects to the house page otherwise, if not, it redirects to the login page.

Middleware is often created by executing the subsequent command −

php artisan make:middleware

Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Example

Observe the following example to understand the middleware mechanism −

Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −

php artisan make:middleware AgeMiddleware

Step 2 − After successful execution of the command, you will receive the following output −

Step 3 − AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.


use Closure;
class AgeMiddleware {
public function handle($request, Closure $next) {
return $next($request);
}
}

Registering Middleware
We need to register each and each middleware before using it. There are two types of Middleware in Laravel.

  • Global Middleware
  • Route Middleware

The Global Middleware will run on every HTTP request of the appliance , whereas the Route Middleware are going to be assigned to a selected route. The middleware 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 middleware.

To register the global middleware, list the class at the end of $middleware 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,
];

To register the route-specific middleware, 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

We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.

The following is the code for app/Http/Kernel.php −


'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'Age' => \App\Http\Middleware\AgeMiddleware::class,
];
}

Middleware Parameters
We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you would like to authenticate the action supported role, this will be achieved by passing parameters with middleware. The middleware that we create contains the subsequent function and that we can pass our custom argument after the $next argument.

public function handle($request, Closure $next) {
return $next($request);
}

Example

Step 1 − Create RoleMiddleware by executing the following command −

php artisan make:middleware RoleMiddleware

Step 2 − After successful execution, you will receive the following output −

Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.


use Closure;
class RoleMiddleware {
public function handle($request, Closure $next, $role) {
echo "Role: ".$role;
return $next($request);
}
}

Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.

Step 5 − Execute the following command to create TestController −

php artisan make:controller TestController --plain

Step 6 − After successful execution of the above step, you will receive the following output −

Step 7 − Copy the following lines of code to app/Http/TestController.php file.

app/Http/TestController.php


use App\Http\Requests;
use App\Http\Controllers\Controller;
class TestController extends Controller {
public function index() {
echo "
Test Controller.";
}
}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('role',[
'middleware' => 'Role:editor',
'uses' => 'TestController@index',
]);

Step 9 − Visit the following URL to test the Middleware with parameters

http://localhost:8000/role

Step 10 − The output will appear as shown in the following image.

Terminable Middleware
Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method within the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method are often created as shown within the following code.

Example

Step 1 − Create TerminateMiddleware by executing the below command.

php artisan make:middleware TerminateMiddleware

Step 2 − The above step will produce the following output −

Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.


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 "
Executing statements of terminate method of TerminateMiddleware.";
}
}

Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware.

Step 5 − Execute the following command to create ABCController.

php artisan make:controller ABCController --plain

Step 6 − After the successful execution of the URL, you will receive the following output −

Step 7 − Copy the following code to app/Http/ABCController.php file.

app/Http/ABCController.php


use App\Http\Requests;
use App\Http\Controllers\Controller;
class ABCController extends Controller {
public function index() {
echo "
ABC Controller.";
}
}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('terminate',[
'middleware' => 'terminate',
'uses' => 'ABCController@index',
]);

Step 9 − Visit the following URL to test the Terminable Middleware.

http://localhost:8000/terminate

Step 10 − The output will appear as shown in the following image.

Namespaces can be defined as a class of elements in which each element has a unique name to that associated class. It may be shared with elements in other classes.

Declaration of namespace

The use keyword allows the developers to shorten the namespace.

use <namespace-name>;

The default namespace used in Laravel is App, however a user can change the namespace to match with web application. Creating user defined namespace with artisan command is mentioned as follows −

php artisan app:name SocialNet

The namespace once created can include various functionalities which can be used in controllers and various classes.