0% found this document useful (0 votes)
36 views62 pages

INT221

Laravel

Uploaded by

Piyush Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views62 pages

INT221

Laravel

Uploaded by

Piyush Verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Laravel Request Lifecycle

• The Laravel request lifecycle is a series of steps that a request goes


through from the moment it enters the Laravel application until a
response is sent back to the client

• Understanding this lifecycle is crucial for grasping how Laravel


processes and handles requests
Incoming Request:
• The lifecycle begins when a request enters the Laravel application
through the public/index.php file. This is the front controller of the
application.

• The index.php file loads the Composer generated


autoloader definition, and then retrieves an instance of
the Laravel application from bootstrap/app.php. The
first action taken by Laravel itself is to create an
instance of the application / service container.
• All requests are directed to this file by your web server configuration.
The index.php file doesn't contain much code. Rather, it is a starting
point for loading the rest of the framework.
Autoloading:
• Composer's autoload file is included to load all the necessary classes
and dependencies.
Bootstrapping:
• Laravel's framework is bootstrapped, which means initializing and
setting up the essential components. This includes loading
environment variables, configuration settings, and service providers.
HTTP / Console Kernels
• the incoming request is sent to either the HTTP kernel
or the console kernel, depending on the type of request
that is entering the application. These two kernels serve
as the central location that all requests flow through.

• The HTTP kernel extends the Illuminate\Foundation\


Http\Kernel class, which defines an array of
bootstrappers that will be run before the request is
executed
• The HTTP kernel also defines a list of HTTP middleware
that all requests must pass through before being
handled by the application. These middleware handle
reading and writing the HTTP session, determining if the
application is in maintenance mode, verifying the CSRF
token, and more.

• The method signature for the HTTP kernel's handle


method is quite simple: it receives a Request and
returns a Response. Think of the kernel as being a big
black box that represents your entire application. Feed it
HTTP requests and it will return HTTP responses.
Service providers
• One of the most important kernel bootstrapping actions is loading the
service providers for your application.

• All of the service providers for the application are configured in the
config/app.php configuration file's providers array.

• Laravel will iterate through this list of providers and instantiate each
of them.
• Service providers are responsible for bootstrapping all of the
framework's various components, such as the database, queue,
validation, and routing components.

• Essentially every major feature offered by Laravel is bootstrapped and


configured by a service provider.

• Since they bootstrap and configure so many features offered by the


framework, service providers are the most important aspect of the
entire Laravel bootstrap process
Service Providers Registration:
• Laravel registers all the service providers listed in the config/app.php
file. Service providers are responsible for binding services into the
service container and performing various bootstrapping tasks.
Request Handling:
• The request is handed over to the HTTP kernel (App\Http\Kernel),
which processes the request through a series of middleware layers.
Middleware can manipulate the request or response, perform
authentication, logging, and other tasks.
Routing:
• After passing through the middleware, the request is sent to the
router (App\Providers\RouteServiceProvider). The router determines
which controller and action should handle the request based on the
routes defined in the routes/web.php or routes/api.php files.
Controller Method Execution:
• The designated controller method is executed. Controllers contain the
logic to process the request, interact with models and services, and
prepare the response.
Response Preparation:
• After the controller processes the request, it returns a response
object. This response can be a view, JSON data, a file download, or
any other type of response.
Response Middleware:
• The response passes back through any response middleware that may
alter the response before it is sent to the client.
Sending Response:
• Finally, the response is sent back to the client's browser. This is the
end of the request lifecycle.
Terminating Middleware:
• After the response is sent, any terminating middleware (middleware
that needs to perform tasks after the response has been sent) is
executed.

• Throughout this lifecycle, Laravel provides several extension points


and hooks (such as middleware and service providers) to customize
the request handling process according to the application's needs
Routing
• In Laravel, all requests are mapped with the help of
routes. Basic routing routes the request to the
associated controllers
• Routing in Laravel includes the following categories
• Basic Routing
• Route parameters
• Named Routes
Basic Routing
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 most basic Laravel routes accept a URI and a


closure, providing a very simple and expressive method
of defining routes and behavior without complicated
routing configuration files:
Routes:
• Routes are actually the web URLs that you can visit in
your web application.

• For example /home, /profile, /dashboard etc are all


different routes that one can create in a Laravel
Application.
Creating Routes
• In Laravel, all of our routes are going to be written
in routes/web.php file as this directory is made standard
for all our web-related routes.

• Open this file and route with Laravel, write to the end of
this file.
Syntax

// Syntax of a route
Route::request_type('/url', 'function()’);

For example
Route::get('/sayhello', function() {
return 'Hey ! Hello';
})
The Default Route Files

• All Laravel routes are defined in your route files, which are located in
the routes directory.

• These files are automatically loaded by Laravel using the configuration


specified in your application's bootstrap/app.php file.

• For most applications, we will begin by defining routes in your


routes/web.php file.
• The routes defined in routes/web.php may be accessed by entering
the defined route's URL in your browser.

• For example, you may access the following route by navigating to


http://example.com/user in your browser:
Available Router Methods

• Route::get($uri, $callback);
• Route::post($uri, $callback);
• Route::put($uri, $callback);
• Route::patch($uri, $callback);
• Route::delete($uri, $callback);
• Route::options($uri, $callback);
Redirect Routes

• If you are defining a route that redirects to another URI, you may use
the Route::redirect method.

• This method provides a convenient shortcut so that you do not have


to define a full route or controller for performing a simple redirect
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

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.
Route::get('user/{name?}’, function ($name = ‘INT221’)
{
return $name;
}
);
Named Routes
• Named routes is an important feature in the Laravel
framework.

• It allows you to refer to the routes when generating


URLs or redirects to the specific routes
• We can define the named routes by chaining the name
method onto the route definition:
Route::get('student/details', function()
{
//
}) -> name('student_details');
Laravel - Views

• In MVC framework, the letter “V” stands for Views.

• It separates the application logic and the presentation


logic. Views are stored in resources/views directory
Example

• Observe the following example to understand more


about Views −
• Step 1 − Copy the following code and save it
at resources/views/test.php
<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
Route::get('/test', function() {
return view('test');
});
Passing Data to Views

• While building application it may be required to pass


data to the views.

• Pass an array to view helper function. After passing an


array, we can use the key to get the value of that key in
the HTML file.
Example

• Observe the following example to understand more


about passing data to views
• Step 1 − Copy the following code and save it
at resources/views/test.php
<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’=>’Mamta sharma’]);
});
• Step 3 − The value of the key name will be passed to
test.php file and $name will be replaced by that value.
• Step 4 − Visit the following URL to see the output of
the view
Sharing Data with all Views

• We have seen how we can pass data to views but at


times, there is a need to pass data to all the views.
Laravel makes this simpler.

• There is a method called share() which can be used for


this purpose
• The share() method will take two arguments, key and
value.

• Typically share() method can be called from boot


method of service provider.

• We can use any service


provider, AppServiceProvider or our own service
provider.
Example
• Observe the following example to understand more about
sharing data with all views −
• Step 1 − Add the following line
in app/Http/routes.php file.
• app/Http/routes.php
Route::get('/test', function() {
return view('test');
});

Route::get('/test2', function() {
return view('test2');
});
• Step 2 − Create two view files
— test.php and test2.php with the same code. These
are the two files which will share data.

• Copy the following code in both the


files. resources/views/test.php &
resources/views/test2.php
<html>
<body>
<h1><?php echo $name; ?></h1>
</body>
</html>
• Change the code of boot method in the
file app/Providers/AppServiceProvider.php as
shown below.

• (Here, we have used share method and the data that we


have passed will be shared with all the
views.) app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot() {
view()->share('name’, Mamta sharma');
}
/**
* Register any application services.
*
* @return void
*/
public function register() {
}
Creating Responses
• Strings & Arrays - All routes and controllers should return a
• response to be sent back to the user's browser.

• Laravel provides several different ways to return responses.


• The most basic response is returning a string from a route or
controller. The framework will automatically convert the string
into a full HTTP response:

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

return 'Hello World’;


}
• In addition to returning strings from your routes and
• controllers, you may also return arrays.

• The framework will automatically convert the array into a


• JSON response:

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

return [1, 2, 3];

});
Attaching Headers
• The response can be attached to headers using the
header() method.
• We can also attach the series of headers as shown in
the below sample code.
• In Laravel, the header() method is used to attach HTTP
headers to a response. HTTP headers provide essential
information about the request or response, and they
play a crucial role in web communication.

• Here are the main reasons why you might use the
header() method in Laravel responses:
1. Customizing Response Behavior:HTTP headers can control how the
client (e.g., a web browser) or intermediate servers (e.g., proxies)
handle the response.
2. Control caching:his prevents the client from caching the response.
3. Adding Custom Metadata:You can use headers to add custom
metadata to your response that might be useful for clients or other
services
4. Security Enhancements
5. Handling Authentication and Authorization
• Syntax
return response($content,$status)
->header('Content-Type', $type)
->header('X-Header-One', 'Header Value')
->header('X-Header-Two', 'Header Value');
Attaching Cookies
• The withcookie() helper method is used to attach
cookies.

• The cookie generated with this method can be attached


by calling withcookie() method with response
instance.

• By default, all cookies generated by Laravel are


encrypted and signed so that they can't be modified or
read by the client
What is a JSON Response?
• A JSON response is an HTTP response that returns data in JSON
format.

• It is commonly used in web APIs to communicate data between the


server (backend) and the client (frontend).

• The client (like a browser or mobile app) makes a request to the


server, and the server responds with data in JSON format
Why Use JSON in Laravel?
• Standard Format: JSON is a universal data format, making it ideal for
exchanging data between different systems, such as a frontend
application (e.g., React, Vue.js) and a backend (Laravel).

• Lightweight: JSON is less verbose than XML, making it a preferred


format for web services where bandwidth efficiency is critical.

• Native Support: Laravel has built-in support for generating JSON


responses using the json() method, making it easy to return
structured data.
How to Create JSON Responses in
Laravel?
• In Laravel, you can create a JSON response using the response()-
>json() method.

• This method takes an array of data and converts it to JSON format


before returning it to the client
Basic Example:

return response()->json([
'status' => 'success',
'message' => 'This is a JSON response'
]);
Key Features of JSON Responses:
• Structured Data: JSON responses allow you to return complex, nested
data structures.

• Custom Headers: You can attach custom HTTP headers to JSON


responses to convey additional metadata.

• Cookies: JSON responses in Laravel can also include cookies, making it


easy to manage state or track sessions.
Common Use Cases:
• APIs: JSON responses are widely used in RESTful APIs, where data is
exchanged between a server and a client application.

• AJAX Requests: When using AJAX in web development, the server


often returns a JSON response to update parts of a web page
dynamically.

• Microservices: JSON is a popular format for communication between


microservices due to its simplicity and language-agnostic nature
Advantages of Using JSON
Responses:
• Interoperability: JSON is supported by almost all programming
languages, making it an excellent choice for cross-platform
communication.

• Readability: JSON is easy to understand for both humans and


machines, which improves maintainability.

• Performance: JSON is less bulky than XML, leading to faster data


transmission and processing

You might also like