Home >>Laravel Tutorial >Laravel Request

Laravel Request

Accessing the Request - Laravel Tutorial

To retrieve an occurrence or instance of the current HTTP laravel request object through dependency injection, you need to type-hint the Illuminate\Http\Request class on your controller system or method. The service container will automatically insert or inject the incoming request instance.  

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
class UserController extends Controller
{
   /**
    * Store a new user.
    *
    * @param  Request $request
    * @return Response
    */
   public function store(Request $request)
   {
       $name = $request->input('name');
 
       //
   }
}

Dependency Injection & Route Parameters

If the input is also getting expected by the controller method from a route parameter, you must list your route parameters following your different dependencies. For instance, if your route is determined like so:   Route::put('user/{id}', 'UserController@update'); You can, however, type-hint the Illuminate\Http\Request furthermore obtain or access your route parameter id by establishing your controller method as follows:  

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
class UserController extends Controller
{
   /**
    * Update the specified user.
    *
    * @param  Request $request
    * @param  string $id
    * @return Response
    */
   public function update(Request $request, $id)
   {
       //
   }
}

 

Accessing The Request Through Route Closures

You can additionally type-hint the Illuminate\Http\Request class on a laravel request object route Closure. The service container will automatically include or append the incoming request inside the Closure when it is performed:  

use Illuminate\Http\Request;



Route::get('/', function (Request $request) {

   //

});

 

Request Path & Method

For analysing the HTTP request for your application plus enlarges the Symfony\Component\HttpFoundation\Request class The Illuminate\Http\Request instance renders a diversity of systems or methods. We will consider some of the Utmost vital systems or methods below.  

Retrieving the Request Path

laravel request has file regarding path method declares as well as returns the request's path erudition. The path method will return foo/bar: if the incoming request is targeted at http://domain.com/foo/bar.  

$uri = $request->path();

  The ‘is’ method enables you to validate that the incoming request path meets a furnished or given pattern. You can utilize the * character as a wildcard when appropriating this method:  

if ($request->is('admin/*')) {

    //

}

  Retrieving the Request URL You can apply or use the URL or fullUrl methods to recover or retrieve the full URL for the incoming request. The URL method will return the URL outwardly the query string, while the fullUrl method comprises the query string:  

// Without Query String...

$url = $request->url();



// With Query String...

$url = $request->fullUrl();

 

Retrieving the Request Method

The method will render or can say return the HTTP verb concerning the request. You can apply or use the ‘isMethod’ method to establish and analyse that the HTTP verb coordinates a given string:  

$method = $request->method();



if ($request->isMethod('post')) {

   //

}

 

PSR-7 Requests

The PSR-7 standard defines interfaces for HTTP communications messages, including requests and acknowledgments. If you would wish to receive an instance of a PSR-7 application or request instead of a request level, you will initially require to install and establish some libraries. Laravel works with the Symfony HTTP Message Bridge element to transform typical Laravel requests and acknowledgments or responses into PSR-7 congenial implementations:   composer require symfony/psr-http-message-bridge composer require zendframework/zend-diactoros   You may concern a PSR-7  laravel request through type-hinting the request interface on your route Closure or controller method: Once you have installed these libraries.  

use Psr\Http\Message\ServerRequestInterface;



Route::get('/', function (ServerRequestInterface $request) {

   //

});

 

Input Trimming & Normalization

Laravel comprises the TrimStrings plus ConvertEmptyStringsToNull middleware in your application's global middleware stack by default. These middleware are registered or listed in the stack by the App\Http\Kernel class. Such middleware will trim all incoming string entries on the request, also transform any blank or empty string fields to null, enables you do not have to bother about these normalization concerns in your routes including controllers.   If you would prefer to hinder this function or behaviour, you are allowed to eliminate the two middleware from your application's middleware stack by excluding them from the $middleware feature or property of your  App\Http\Kernel class.   Retrieving Input Retrieving All Input Data You can further reclaim or retrieve all of the input data as an array utilizing the all method:  

$input = $request->all();

 

Retrieving an Input Value

Applying several uncomplicated methods, you may be able to obtain or access all of the user input from your Illuminate\Http\Request instance outwardly bothering regarding which HTTP verb was applied for the laravel request. Notwithstanding the HTTP verb, the input method may be applied to recover or retrieve user input:  

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

  You may give or pass a default value as the second following argument to the input method. This secondary value will be rendered or returned if the requested input value is not already there on the request:  

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

  When working regarding forms that include array data inputs, you must use "dot" notation to obtain or access the arrays:  

$name = $request->input('products.0.name');

$names = $request->input('products.*.name');

  You can call the input method outwardly any arguments to regain or retrieve all of the input values as an associative array:  

$input = $request->input();

 

Retrieving Input from The Query String

The query method will solely recover or retrieve values from the query string: While the input method retrieves or regains values from whole request payload (including the query string).  

$name = $request->query('name');

  If the requested query string value data is not already there, the following or the second provided the argument to this method will be returned:  

$name = $request->query('name', 'Helen');

  You can call the query method outwardly any arguments to regain or retrieve all the query string values as an associative array:  

$query = $request->query();

 

Retrieving Input Via Dynamic Properties

You are also allowed to obtain or access user input utilizing dynamic characteristics on the Illuminate\Http\Request instance. For instance, if one of your application's forms includes a name field, you can locate the value of the field like so:  

$name = $request->name;

  When applying dynamic properties laravel request object, Laravel will initial aspect for the parameter's value in the request payload. If it is not available, Laravel will seek for the field in the route parameters.  

Retrieving JSON Input Values

When addressing JSON requests to your application, you are allowed to obtain the JSON data through the input method as long as the Content-Type header of the appeal or request is well set to application/json. You may indeed apply "dot" syntax to discover or dig deep into JSON arrays:  

$name = $request->input('user.name');

 

Retrieving a Portion Of The Input Data

You can apply the "only" and 'except' methods on laravel request object if you demand to retrieve a subset of the input data. Both of these methods receive a single array or a dynamic table list of arguments:  

$input = $request->only(['username', 'password']);



$input = $request->only('username', 'password');



$input = $request->except(['debit_card']);



$input = $request->except('debit_card');

 

Ascertaining If an Input Value Is Present

You should use the 'has' method to conclude if a value is already there on the request. The ‘has’ method declares true if the provided value is present on the request:  

if ($request->has('name')) {

   //

}

When delivered an array, the 'has' method will conclude if each of the particularized values is present:

if ($request->has(['name', 'address'])) {

   //

}

  If you would wish to ascertain if a value is already there or present on the request plus is not negative or can say empty, you can apply the 'filled' method:  

if ($request->filled('name')) {

   //

}

  Old Input laravel request has file that enables you to grasp input from one request during the subsequent request. This characteristic is expressly serviceable for re-populating forms later or after identifying validation failures or in other words errors. Though, if you are exercising Laravel's incorporated validation features, it is incredible you will require to use these methods manually, as a few of Laravel's built-in validation facilities will call them automatically.  

Flashing Input to the Session

The flash method on the Illuminate\Http\Request class will flash the current input to the session so that it is accessible throughout the user's following request to the application:  

$request->flash();

  You can further utilize the 'flashOnly' and 'flashExcept' methods to flash a subset of the request data to the session. These methods are helpful for administering sensitive knowledge or information such as identifications of passwords out of the session:  

$request->flashOnly(['username', 'address']);
$request->flashExcept('password');

 

Flashing Input Then Redirecting

As you frequently will need to flash input to the session moreover then redirect to the preceding page, you can readily chain input flashing onto a redirect applying the 'withInput' method:  

return redirect('form')->withInput();



return redirect('form')->withInput(

   $request->except('password')

);

Retrieving Old Input

Apply the 'old' method on the Request instance to reclaim or retrieve flashed input from the previous request. The 'old' method will draw the earlier flashed input data from the session:

$username = $request->old('username');

  laravel request object also implements a global 'old' helper. If you are representing old input inside a Blade template, it is plentiful handy to apply the 'old' helper. If no old input subsists for the addressed field,  null will be returned:  

<input type="text" name="username" value="{{ old('username') }}">

  Cookies

Reclaiming or Retrieving Cookies from Requests

Request laravel framework creates all the cookies and is encrypted as well signed with an authentication code, indicating they will be counted invalid if the client modifies. Apply the cookie method on an 'Illuminate\Http\Request' instance: to recover or retrieve a cookie value from the request.  

$value = $request->cookie('name');



Alternatively, you can apply the Cookie facade to obtain cookie values:



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

 

Appending or Attaching Cookies to Responses

You can add a cookie to an outgoing Illuminate\Http\Response instance utilizing the 'cookie' method. You must pass the name, value, and a number of minutes the cookie should be regarded valid to this method:  

return response('You are impressive')->cookie(

   'name', 'value', $minutes

);

  The cookie method further receives several extended arguments, used less generally. Frequently, these arguments have the corresponding meaning plus interest as the arguments that would be contributed to PHP's native 'setcookie' method:  

return response('Here, You can write anything you want')->cookie(

   'name', 'value', $minutes, $path, $domain, $secure, $httpOnly

);

  You can apply the Cookie facade to "queue" cookies for the appendage to the friendly or can say an outgoing response from your application, Alternatively. The queue method allows a Cookie occurrence or instance or the arguments required to construct a Cookie instance. These cookies will be appended to the outgoing acknowledgment before it is transmitted to the browser:  

Cookie::queue(Cookie::make('name', 'value', $minutes));



Cookie::queue('name', 'value', $minutes);

 

Generating Cookie Instances

laravel request has file that comprises the ability to generate Cookies; If you would prefer to create a Symfony\Component\HttpFoundation\Cookie instance that can be assigned to an acknowledgment instance at a succeeding time, you may apply the global cookie helper. This cookie will not be given back to the client except it is connected to a response instance:  

$cookie = cookie('name', 'value', $minutes);



return response('Hello World')->cookie($cookie);

 

Retrieving Uploaded Files

You are also allowed to obtain uploaded records or files from a Illuminate\Http\Request instance utilizing the file method or applying dynamic properties. The file method states or returns an instance of the  Illuminate\Http\UploadedFile class, which prolongs the PHP SplFileInfo class and implements a diversity of methods for associating with the file:   You can conclude if a record or file is already there or present in the request utilizing the 'hasFile' method:  

if ($request->hasFile('photo')) {

   //

}

 

Validating Successful Uploads

In extension to monitoring if the file is already available, you may check that no problems were uploading the data file through the 'isValid' method:  

if ($request->file('photo')->isValid()) {

   //

}

 

File Paths & Extensions

The UploadedFile class further comprises request laravel methods for locating or accessing the file's fully-qualified pathway plus its expansion. The 'extension' method will endeavor to figure out the file's extension based on its contents. This extension may be distinct from the extension that was provided by the client:  

$path = $request->photo->path();
$extension = $request->photo->extension();

 

Other File Methods

There are no doubt a description of different methods accessible on UploadedFile instances. Check out the API documentation for the class for further knowledge concerning these methods.  

Storing Uploaded Files

You will typically utilize one of your configured filesystems to save an uploaded file. The 'UploadedFile' class has a store method which will relocate or move an uploaded file to one of your disks, which may be a place on your local filesystem or indeed a cloud storage location.   The store method allows the path where the file should be saved relevant to the filesystem's configured root record directory. This path should not include a file name because an individual unique ID will automatically be created to assist as the file name.   The 'store' method of the laravel request object additionally acquires an unrestricted second argument for the name of the disk that should be applied to store the file. The method will deliver or return the path of the file corresponding to the disk's root:  

$path = $request->photo->store('images');
$path = $request->photo->store('images', 's3');

  If you do not desire to generate a file name automatically, you can apply the 'storeAs' method, which holds or accepts the path, file name, and disk name as its arguments:  

$path = $request->photo->storeAs('images', 'filename.jpg');

 

$path = $request->photo->storeAs('images', 'filename.jpg', 's3');

 

Configuring Trusted Proxies

When operating your applications backward a measurement or load balancer that concludes TLS / SSL documents or certificates, you may discern your application seldom does not create HTTPS links. This is because your application is being forwarded traffic of your load balancer on port 80 and does not know it should produce reliable as well as secure links.   To resolve those above, you may exercise or use the App\Http\Middleware\TrustProxies middleware, involved in your Laravel application, which enables you to immediately customize the load balancers or proxies, presumed by your application. Your trusted proxies should be arranged or listed as an array on the $proxies characteristic or properties of this middleware. In extension to configuring the presumed proxies, you can configure the proxy $headers that should be entrusted.  

<?php



namespace App\Http\Middleware;



use Illuminate\Http\Request;

use Fideloper\Proxy\TrustProxies as Middleware;



class TrustProxies extends Middleware

{

   /**

    * The trusted proxies for this application.

    *

    * @var array

    */

   protected $proxies = [

       '192.168.1.1',

       '192.168.1.2',

   ];



   /**

    * The headers that should be used to detect proxies.

    *

    * @var string

    */

   protected $headers = Request::HEADER_X_FORWARDED_ALL;

}

 

Trusting All Proxies

If you are implementing Amazon AWS or different "cloud" load balancer provider, you may be unable to identify the IP addresses of your exact balancers. In this instance, you can apply * to trust all proxies:  

/**

* The trusted proxies for this application.

*

* @var array

*/

protected $proxies = '*';

Laravel request has file containing all the necessary application or request for distinct function available for different desirable utilization of several exponential functions.


No Sidebar ads