Understanding Laravel Request Handling Tutorial with example

Understanding Laravel HTTP Requests tutorial with example

After designing the beautiful front-end interface (using HTML, CSS, Bootstrap, JS), the next step is to implement server-side code to retrieve the request input dataprocess it and send back responses.

This tutorial will explain how Laravel retrieves input data from the incoming HTTP request. The incoming HTTP request can contain plain text data, images, and documents.

Here, You will learn all the methods to get HTML form data at server-side using Laravel Request handling mechanism.

How Laravel handles incoming HTTP requests?

Laravel provides a very simple and robust mechanism to handle HTTP requests data. Laravel implement the facade design pattern to provide a unified interface for handling user requests.

We will have a detailed chapter on Laravel facade, but let’s have a quick view of the facade in Laravel.

Read our detailed chapter Laravel Request Lifecycle, How Laravel request received and served.

What is a facade in Laravel?

A Facade is a design pattern in an OOPS which wraps a set of complex interfaces to provide a simpler and unified interface. Laravel comes with many inbuilt facades which provide unified access to all of Laravel’s featuresSome of the common facades are Request, Cache, Cookie, etc classes which provide a very simpler interface to users. Laravel facades act as “static proxies” to underlying classes.

 

All of the Laravel facades are defined in the Illuminate\Support\Facades namespace. So, we can easily access a facade like this:

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Cookie;

Route::get('/cache', function () {
return Cache::get('key');
});


Understanding Laravel Request Handling

First of all, We will learn what is the Request object in Laravel, How it is generated and what does it contain. The Request object plays a major role in Laravel Request Lifecycle while serving the incoming request and sending back responses. Let’s understand Laravel request Object in easy steps – how Laravel request is processed:

  • 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. So, this means that HTML form input data become part of Request object at server-side.
  • Then, the Request passed through many layers and process the data.
  • The application then generates the Illuminate Response object.
  • Finally, the response is sent back through those layers and returned to the end user (i.e client web browser).

 

Checkout Laravel Tutorial Guide for Beginners

 

The Laravel Request Facade:

The Illuminate Request class is a Laravel-specific extension of Symfony’s HttpFoundation\Request object. Laravel provides a unified way of retrieving all types of user input data.

In native PHP code, you might find yourself looking to $_SERVER, $_GET, $_POST, and
other combinations of globals and processing logic to get information about the current
user’s request.

 

Must read guides on OpenCart and JavaScript:

Powerful Features of JavaScript That Every Developer Should Know!!

How PHP Connect to MySQL Tutorial with Example

How to install OpenCart on LAMP/WAMP Server?

What is OpenCart? Features of OpenCart!

Ultimate PHP Composer Package Manager Tutorial

Symfony’s Request object instead collects all of the information necessary to represent
a single HTTP request into a single object.

List of Laravel Request methods

Following is the list of the commonly used set of methods to process incoming requests:

  • all() – returns an array of all user-provided input.
  • input(fieldName) returns the value of a single user-provided input field.
  • method() returns the method (GET, POST, PATCH, etc.) used to access this route.
  • path() returns the path (without the domain) used to access this page; e.g., for
    http://www.techcluesblog.com/abc/xyz it would return abc/xyz.
  • only(fieldName|[array,of,field,names]) returns an array of all user provided input for the specified field name(s).
  • except(fieldName|[array,of,field,names]) returns an array of all user provided input except for the specified field name(s).
  • exists(fieldName) returns a boolean of whether or not the field exists in the input.
  • URL() returns the URL (with the domain) used to access this page; e.g., for HTTP://
    www.techcluesblog.com/xyz it would return http://www.techcluesblog.com/xyz.
  • ip() returns the user’s IP address.
  • file() returns an array of all uploaded files, or, if a key is passed (the file upload field name), returns just the one file.
  • json() returns a ParameterBag if the page had JSON sent to it. This retrieves the Laravel request JSON data.

Now, time to understand how to use the Laravel Request object to retrieve the user input data.

Laravel get url parameters – the path() and url() methods are used to get URL parameters.

Retrieving The Request resources in Laravel

The request can be processed either in route closure, middleware of controller function associated with the route.

Accessing a Request Object in Laravel

Laravel developers need not create new Laravel Request objects to retrieve the user input data. Laravel has inbuilt functionality, You just need to learn the Request methods() required to retrieve the data.

Below is a sample code to retrieve all the input data:

use Illuminate\Http\Request;
class StudentController extends Controller
{
   public function index(Request $request)
   {
      $inputData = $request->all(); ///retrieves all the passed input data....
   }
}

Retrieving The Request URI

The “path” method of Request object can be invoked to retrieve the requested URI. The url() method can be used to get the full URL. It can be achieved as below:

$MyURI = $request->path();

Determining If The Request Is Over HTTPS

if (Request::secure())
{
// yes its HTTPS request
}

Determine If The Request Is Using AJAX – How to check if the Laravel request is using Ajax or not?

if (Request::ajax())
{
//This is AJAX request..
}

Retrieving The Request Method – checking whether it gets/post/delete.

The following method can be used to check the type of request. The method will return the HTTP verb for the request. You may use the isMethod method to verify that the HTTP verb matches a given string:

$method = $request->method();
if ($request->isMethod('post'))

{ //This is POST request.. }

Get The Current Laravel Request URL

The url() method will return the URL without the query string while the fullUrl() method complete URL with the query string:

// Without Query String...
$url = $request->url();

 

// With Query String… $url = $request->fullUrl();

Retrieving All Input Data

You may also retrieve all of the input data as an array using all() method:

$input = $request->all();

Retrieving a specific Input Value

$name = $request->input('name');
$name = $request->input('age');

Retrieving A Default Value If The Input Value Is Absent

You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request:

$name = $request->input('name', 'TechCluesBlog');

Laravel Cookies Handling

Cookies in Laravel application are attached to the requests and responses which developer need to interact differently. Let’s take a brief look at Request function to retrieve Cookies in Laravel:

Cookies in Laravel can exist in three places in Laravel:

  • Cookies can come via the request, which means the user had the cookie when they visited the page. You can read that with the Laravel Cookie facade, or you can read it off of the request object.
  • They can also be sent out with a response, which means the response will instruct the user’s browser to save the cookie for future visits. You can do this by adding the cookie to your response object before returning it.
  • Finally, a cookie can be queued. If you use the Cookie facade to set a cookie, you have put it into a “CookieJar” queue, and it will be removed and added to the response object by the AddQueuedCookiesToResponse middleware.

 

TIPAll cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.

Retrieving A Cookie Value

$value = Cookie::get('name');

Attaching A New Cookie To A Response

$response = Response::make('Hello World');
$response->withCookie(Cookie::make('name', 'value', $minutes));

Creating A Cookie That Lasts Forever

$cookie = Cookie::forever('name', 'value');

The complete list of Laravel Cookie Facade methods

The Cookie facade is the most full-featured option, allowing you to not only read and make cookies but also to queue them to be added to the response. It provides the following methods:

  • Cookie::get($key) – To pull the value of a cookie that came in with the request, you can just run this query.
  • Cookie::get(‘cookie-name’)  – This is the simplest option.
  • Cookie::has($key) – You can check whether a cookie came in with the request using
  • Cookie::make(…params) If you want to make a cookie without queuing it anywhere.

Laravel File Upload handling

Every input element passed from the client application is processed using Laravel Request object whether it is simple text, image or any document.

Retrieving An Uploaded File

$file = Input::file('photo');

Determining If A File Upload Was Successful

if (Input::hasFile('photo'))
{
   / /Yes, the file upload was successful.
}

Moving An Uploaded File – from one location to another location

Input::file('photo')->move($destinationPath);
Input::file('photo')->move($destinationPath, $fileName);

Determining If An Uploaded File Is Valid

if (Input::file('photo')->isValid())
{
   //Yes, the file is valid.
}

Retrieving The Path To An Uploaded File

$path = Input::file('photo')->getRealPath();

Retrieving The Original Name Of An Uploaded File

$name = Input::file('photo')->getClientOriginalName();

Retrieving The Extension Of An Uploaded File

$extension = Input::file('photo')->getClientOriginalExtension();

Retrieving The Size Of An Uploaded File

$size = Input::file('photo')->getSize();

Retrieving The MIME Type Of An Uploaded File

$mime = Input::file('photo')->getMimeType();

 

Conclusion

Now, we have learned all about Laravel request handling. The list of Laravel request methods we discussed can be used to retrieve the various type of input data – text, images, files, and documents.

In the next tutorial, we will learn about Laravel Request Validation methods.

Further Reading

Laravel Request official documentation

Laravel Request Tutorial

Laravel News Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *