You are on page 1of 8

Q-1. Explain Laravel’s Request Lifecycle.

OR

Explain the life cycle of Laravel Request object? How can we access it?

Every request coming into a Laravel application, whether generated by an HTTP request or a
command-line interaction, is immediately converted into an Illuminate Request object, which
then crosses many layers and ends up being parsed by the application itself. The application then
generates an Illuminate Response object, which is sent back out across those layers and finally
returned to the end user.

Steps of Laravel request lifecycle:


1. First of all, the entry point of all HTTP request is public/index.php
2. Load the composer generated the vendor/autoload.php file aad get the new laravel
application object from bootstrap/app.php
3. Then ,the request is sent to HTTP kernels which calls boot strappers to load configuration,
register and call service providers
4. HTTP kernel handles the request and dispatches it to a router.
5. Router fined the exact route and calla s controller function.
6. Controller function validates the input, calls database models and calls views.
7. The HTTP response sent back to incoming users.

STEP1 – Entry point public/index.php

 The main entry point for all the HTTP requests to a Laravel application is
the public/index.php file.

 The HTTP web requests are directed to this file by your web server (whether using Apache or
Nginx) configuration.

 The index.php file is just triggering point, doesn’t contain much code. It is a starting point for
loading the rest of the Laravel framework components.

STEP2 – bootstrap/app.php script

 All the HTTP web requests from web applications are directed through
the public/index.php script file. When the web application is hosted on Apache web server,
then the .htaccess file that ships with Laravel handle the passing of all requests to index.php.
 After a request enters your index.php file, next the bootstrap/start.php file will be loaded.
This file creates the new Laravel Application Object.

 Next, the main index.php file loads the Composer generated autoloader definition and then
retrieves an instance of the Laravel application from bootstrap/app.php script.

 The first step performed by Laravel Framework is to create an instance of the application /
service container.This file creates the new Laravel Application object.

STEP3 -HTTP Console Kernels

 The Laravel HTTP kernel layer acts as a central point for serving all the incoming requests
from users. After the request processed from the bootstrat/app.php script, it sent to HTTP
kernel or console kernel, depending on the type of request from a user.

 The HTTP kernel file is located at – app/Http/Kernel.php

STEP4 -Register Service Providers

 Next step comes to the Laravel Service Providers. Service providers are responsible for
bootstrapping all of the Laravels components, such as the database, queue, validation, and
routing components.

 All of the service providers for the application are configured in the config/app.php
configuration file’s providers array. First, the register method will be called on all providers,
then, once all providers have been registered, the boot method will be called.

STEP5 – Dispatch Request to Router

 Now, all the service providers are registered, your app/Http/routes.php (routes/web.php in
case of Laravel 5.7). Finally, your app/routes.php file will be loaded. When the routes.php file
is loaded, the Request object is sent to the application so that it may be dispatched to a route.

 Once the application has been bootstrapped and all service providers have been registered,
the Request will be handed off to the router for dispatching. The router will dispatch the
request to a route or controller, as well as run any route specific middleware.

Q-2 what is the Request Object? How to get basic information about a request?

• Each Request object is intended to represent every relevant piece of information you could care
to know about a user’s HTTP request.

• Request object instead collects all of the information necessary to represent a single HTTP
request into a single object, and then tacks on convenience methods to make it easy to get useful
information from it.

use Illuminate\Http\Request;
class PeopleController extends Controller
{
public function index(Request $request)
{
$allInput = $request->all();
}
}
Getting Basic User Input

Method Description Example

all() returns an array of all $input = $request->all();


user-provided input.

input(fieldName) returns the value of a $name = $request->


single user-provided input('name');
input field.

only(fieldName|[array,of,field,names]) returns an array of all $input = $request->


userprovided only(['username',
'password']);
input for the specified
field name(s).

except(fieldName|[array,of,field,names]) returns an array of all $input = $request-


userprovided >except(['credit_card']);

input except for the


specified field name(s).

exists(fieldName) returns a boolean of $input=$request-


whether or not the field >exists(‘name’);
exists in

the input.

has(fieldName) returns a boolean of if ($request->has('name'))


whether the field exists in
{
the input and is
//
not empty (has a value).
}

json() returns a ParameterBag $request->json();


if the page had JSON sent
to it.

json(keyName) returns the value of the $request->json(‘city’);


given key from JSON sent
to the page.
Q-3 Discuss the process of creating the Response Object in Laravel along with specialized response
types.

OR

What is Response object in Laravel? How can we send response from Laravel? Also explain different
methods to send file as response to browser.

• Similar to the Request object, there’s an Illuminate Response object that represents the response
your application is sending to the end user, complete with headers, cookies, content, and
anything else used for sending the end user’s browser instructions on rendering a page.

Setting headers

• We define a header on a response by using the header() fluent method.

• The first parameter is the header name and the second is the header value.

Route::get('route', function () {

return response('Error!', 400)

->header('X-Header-Name', 'header-value')

Specialized Response Types

• There are also a few special response types for views, downloads, files, and JSON.

• Each is a predefined macro that makes it easy to reuse particular templates for headers or
content structure.

• View responses: The global view() helper to show how to return a template

• for example, view(view.name.here) or something similar.


Download responses

• Sometimes you want your application to force the user’s browser to download a file,whether
you’re creating the file in Laravel or serving it from a database or a protected location.

File responses:

• The file response is similar to the download response, except it allows the browser to display the
file instead of forcing a download. This is most common with images and PDFs.
JSON responses:

• JSON responses are so common that, even though they’re not really particularly complex to
program, there’s a custom response for them as well.

Redirect responses:

• Redirects, returned from a Laravel route, send the user a redirect(often a 301) to another page or
back to the previous page.

• There is a global redirect() function that can be used to create redirect responses,and a global
back() function that is a shortcut to redirect()->back().

– return redirect('account/payment');

– return redirect()->to('account/payment');

– return redirect()->route('account.payment');

– return redirect()->action('AccountController@showPayment');

• If named route or controller needs parameters:

– return redirect()->route('contacts.edit', ['id' => 15]);

– return redirect()->action('ContactsController@edit', ['id' => 15]);

Q-4 How to create custom Middleware in Laravel.

OR

What is Middleware? How it can be created and implemented? Explain with proper code snippet.

• Middlewares in Laravel is nothing but a simple mechanism that helps to filters the HTTP requests
and alter the business logic or executes some action/logics based on the written conditions. In
other words we could say the middlewares are logical layer around our application that analyze
the http requests and alter the application business logic.

• Middlewares can either executes the logics befor or after the particular incoming http request is
handled. Based on this ability of middlewares can be classified as Before / After Middleware. We
will start with learning how to create a middleware then we will jump on defining and using a
middleware in our application.

Creating a middleware :

• Open up your terminal switch to your project directory and run the following artisan command..

– php artisan make:middleware nameOfMiddleware

• This simple command will generate a middleware within your project’s app/Http/Middleware
directory with specified middleware name.

Defining a Middleware:

• Once we have run the artisan make command for middleware we will get a file generated with
following structure.

public function handle($request, Closure $next)

{ //Code

return $next($request);

• We should have to write our business logics within the handle method of our middleware.

Registering a Middleware :

• We can either apply this extra layer of logics (Middlewares) for all the HTTP request that coming
to our application or we could assign the defined middlewares for specific routes.

• Based on this Middlewares can be classified into –

– Global Middlewares

– specific route Middlewares

– Middleware Groups

1. Global Middlewares

a. Global middlewares are middlewares that executes for each and every request to our
application.

2. Specific route Middlewares

a. Specific route Middleware’s are middlewares that executes for specified pre defined
routes.

3. Middleware Groups :

– As the name indicate the middleware group is a grouping of multiple middlewares (of
same kind/category) which are indicated by a single key and this Group key can be
assigned to single route or a set of routes, so that multiple middlewares can be simply
assigned to a single/group of routes at once using a single key.
Setting-up Global middlewares :

– Setting a global middleware that executes for every request is simple. Open up your
projects app/Http/Kernel.php file. You could see 3 different properties defined in the
class ‘$middleware’ , ‘$middlewareGroups ‘ and ‘$routeMiddleware’.

– Simply append your middlewares to the $middleware section as comma separated.

Call middleware

• Once the middleware has been defined in the HTTP kernel, you may use the middleware method
to assign middleware to a route:

Route::get('admin/profile', function () {
//
})->middleware('auth');
• You may also assign multiple middleware to the route:
Route::get('/', function () {
//
})->middleware('first', 'second');

You might also like