Laravel HTTP Requests


Laravel HTTP Requests – The Laravel HTTP Requests is used to retrieve the input field or any string in form of GET and POST method.


Laravel HTTP Requests.

Let us understand how to use laravel HTTP Requests.

Function:-

There are some followings function available in laravel HTTP Requests.

  • 1. Accessing The Request.
  • 2. Input Trimming & Normalization.
  • 3. Retrieving Input.
  • 4. Files.

1. Accessing The Request.

The current Http request via dependencies injection, you should type-hint Illuminate/Http/Request class on your controller method. The incoming request will automatically pushed by the service container.

Let’s look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;

class RequestController extends Controller
{
public function store(Request $request)
    {
        $name = $request->input('name', 'Solid Coupon');
        echo "$name";
    }	
}

Route Path:-

Route::get('request/', 'RequestController@store');
Laravel HTTP Requests

Dependency Injection & Route Parameters

Controller method is also consider input to a route parameter uou should list your route parameter after your other dependencies.

Route::put('user/{id}', 'UserController@update');

Controller Part:-

Let’s look at a simple example.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function update(Request $request, $id)
    {
        echo "Updated Sucessfully!";
    }
}

Accessing The Request Via Route Closures

By using this method we can directly define function in route.

use Illuminate\Http\Request;

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

Retrieving The Request Path, URL And Method

The Path method is used to retrieve the requested URI. The is method is used to retrieve the requested URI which match the particular pattern of the method. The url method is used to get full url.

Example:-

First we have to create a new controller called UriController.

php artisan make:controller UriController –plain
Laravel HTTP Requests

Controller Parts:-

Let's look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UriController extends Controller {
   
   public function index(Request $request){
     
      $path = $request->path();
      echo 'Path Method: '.$path;
      echo '<br>';
     
      $pattern = $request->is('uri/*');
      echo 'is Method: '.$pattern;
      echo '<br>';
      
      $url = $request->url();
      echo 'URL method: '.$url;
   }
}

Route Part:-

Route::get('uri/bar','UriController@index');
Laravel HTTP Requests

2. Input Trimming & Normalization.

Laravel include the TrimString and ConvertEmptyStringToNUll in global middleware stack. this middleware are listed in stack through Kernel class. It will automatically trim all incoming string field on the request and convert empty field to null.

3. Retrieving Input.

We can easily get the input value in Laravel. Doesn't matter what method was used "GET" or "POST". It will get input value for both method the same way.

EXAMPLE

Create a registration form in view directory.

Let's look at a simple example.

<html>

   <head>
      <title>Form Example</title>
   </head>

   <body>
      <form action = "postRegister" method = "post">
         <input type = "hidden" name = "_token" value = "<?php echo csrf_token() ?>">
      
         <table>
            <tr>
               <td>Name</td>
               <td><input type = "text" name = "name" /></td>
            </tr>
         
            <tr>
               <td>Username</td>
               <td><input type = "text" name = "username" /></td>
            </tr>
         
            <tr>
               <td>Password</td>
               <td><input type = "text" name = "password" /></td>
            </tr>
         
            <tr>
               <td colspan = "2" align = "center">
                  <input type = "submit" value = "Register" />
               </td>
            </tr>
         </table>
      
      </form>
   
   </body>
</html>

Create a UserRegistration controller page.

php artisan make:controller UserRegistration --plain
Laravel HTTP Requests

Controller Parts:-

Let's look at a simple example.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class UserRegistration extends Controller {
   public function postRegister(Request $request){
     
      $name = $request->input('name');
      echo 'Name: '.$name;
      echo '<br>';
      
      $username = $request->username;
      echo 'Username: '.$username;
      echo '<br>';
      
      $password = $request->password;
      echo 'Password: '.$password;
   }
}

Route Part:-

Route::get('/register',function(){
   return view('register');
});
Route::post('postRegister',array('uses'=>'UserRegistration@postRegister'));
Laravel HTTP Requests

Old Input

Laravel permits you to keep input from one request to the next request. It is used for re-populating form after detecting validation errors. If you are using validation feature, you will need to use manually this method and validation facilities will call them automatically.

Flashing Input To The Session

The flash method we can use like this:-

$request->flash();

We can also use the flashOnly and flashExcept method to flash a subset of the request data to the session.

$request->flashOnly(['username', 'email']);

$request->flashExcept('password');

Flashing Input Then Redirecting

You will frequently want to flash input to the session and then redirect to the previous page.

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

return redirect('form')->withInput(
    $request->except('password')
);

Retrieving Old Input

If we wnt to get flash input from the previous request. We can use old method on the request.

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

Laravel provides a global old helper. If no old input exist for the given field, the output will be return null.

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

Cookies

Retrieving Cookies From Requests

Laravel framework are created all cookies which is encrypted and signed with authentication code. Means it will be considered invalid if they have been changed by the client. To get cookie value from the request we can use cookie method.

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

Attaching Cookies To Responses

you can aatach cookie using the cookie method. You should pass the name, value and number of minute the cookie should be considered valid to this method.

return response('Hello World')->cookie(
    'name', 'value', $minutes
);

Generating Cookie Instances

If you would like to generate cookie. you may use global cookie helper.

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

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

4. Files.

Retrieving Uploaded Files

You can access uploaded file from the Illuminate/Http/Request using the file
method. The file method return an instance of the Illuminate/Http/UploadedFile class.

$file = $request->file('photo');

$file = $request->photo;

You may determine if a file is present on the request using the hasFile method.

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

Validating Successful Uploads

You can check the validation using isValid method during the uploading the file.

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

File Paths & Extensions

It is used to access the file fully-qualified path and its extension.

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

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

Storing Uploaded Files

To store uploaded file we can use store method which is move an uploaded file to one of your disk.

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

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

If you don't want to file name is automatically generated. You can use the storeAs
method.

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

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

Advertisements

Add Comment

📖 Read More