Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
Understanding laravel request

Understanding Laravel request with example

Aman Jain, November 17, 2021November 22, 2021

Laravel provides a own class to handle the request which is Illuminate\Http\Request. Request is used to retrieve the user input(GET and POST), cookies and files that was submitted during the request.

  • Get the request in controller
  • Get the request in routes
  • Get current request with parameter
  • Accessing path and validating request path
  • Get request URL from current request
  • Get request method and validating request method from current request
  • Get all inputs data from request
  • Get single input value from request
  • Get query params input value from request
  • Get uploaded files from request
  • Let’s understand the request in with example

Get the request in controller

Current Request can be get retrieved in controller by injecting the dependency in controller method.

Class name is Illuminate\Http\Request.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    
    public function store(Request $request)
    {
        $name = $request->input('title');
    }
}

Get the request in routes

We can also fetch the current request input, cookies and files in our routes as well.

use Illuminate\Http\Request;

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

Get current request with parameter

We can also pass multiple parameter to our routes then we can get in controller with request.

in Route

use Illuminate\Http\Request;

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

And in controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller
{
    
    public function store($id,Request $request)
    {
        $name = $request->input('title');
    }
}

Accessing path and validating request path

To get the path in Laravel we use path method and to validate the request path start with then we can use is method .

$uri = $request->path();

For example URL is http://domain.com/user/post/1 then the path will be user/post/1

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

Get request URL from current request

url and fullUrl method is used to get the current request URL, url method return the URL without query string parameter and fullUrl with query string parameter

$url = $request->url();

$urlWithQueryString = $request->fullUrl();

Get request method and validating request method from current request

method and isMethod is used for get the method and validating the request method respectively.

$method = $request->method();

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

Get all inputs data from request

We can retrieve all request post and get variables from request by using all method of request.

$allInput = $request->all();
//or
$allInput = $request->input();

Get single input value from request

We can access the single input by input method or directly from request object

$name = $request->name;

//or

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

// with default value

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

//working with array

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

Get query params input value from request

We can also get query string from URL for example if we have http://domain/post?id=1

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

Get all query params

$allQuery = $request->query();

Get uploaded files from request

file method is used for access the uploaded files in Laravel and to check the file is exists or not we can user hasFile.

$image = $request->file('image');
 //or 
$image = $request->image

//check file exists
$request->hasFile('image');

Let’s understand the request in with example

To understand the request we will take a simple registration form, create routes and controllers. so check below steps

Step 1: Create a laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 2 : Create a controller

Now, create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller PostController

Now, add use Illuminate\Http\Request; and methods

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class PostController extends Controller
{

     /**
     * Show the form to create a new blog post.
     *
     * @return \Illuminate\View\View
     */
    public function create()
    {
        return view('post.create');
    }

    /**
     * Store a new blog post.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, Response $response)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',   // required and email format validation
            'phone_number' => 'required|numeric|digits_between:9,15', // required and number field validation
            'username' => 'required',
        ]); // create the validations
        if ($validator->fails())   //check all validations are fine, if not then redirect and show error messages
        {
            
            return back()->withInput()->withErrors($validator);
            // validation failed redirect back to form

        }
        else
        {
            //handle the form 
        }  
    }
   
}

Here , we added two methods one for to show the form view(create) and store to handle the form submit.

Step 3 : Create the view for form

We have created controller and now we need to create the form so we are creating the view file for it.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Readerstacks laravel 8 request</title>
 <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />
   </head>
    <body class="antialiased">
    <div class="container">
    <!-- main app container -->
    <div class="readersack">
      <div class="container">
        <div class="row">
          <div class="col-md-6 offset-md-3">
            <h3>Laravel 8 request - Readerstacks</h3>
           
            <form method="post" action="{{url('submit-post')}}" name="registerform">
             <div class="form-group">
                <label>Email</label>
                <input type="text" name="email" value="{{ old('email') }}" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <label>Phone number</label>
                <input type="text" name="phone_number"  value="{{ old('phone_number') }}" class="form-control" />
              </div>
              <div class="form-group">
                <label>Username</label>
                <input type="text" name="username"   value="{{ old('username') }}" class="form-control" [ />
              </div>
            <div class="form-group">
                <label>Image</label>
                <input type="file" name="image"    class="form-control" [ />
              </div>
              <div class="form-group">
                <button class="btn btn-primary">Submit</button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
    <!-- credits -->
    <div class="text-center">
      <p>
        <a href="#" target="_top">Laravel 8 http request</a>
      </p>
      <p>
        <a href="https://readerstacks.com" target="_top">readerstacks.com</a>
      </p>
    </div>
  </div>
    </body>
</html>

Step 4 : Create Routes

First step is to create the routes to show the form and submit the form

<?php

use Illuminate\Support\Facades\Route;
use \App\Http\Controllers\PostController;

Route::get('/create-post',[PostController::class, 'create']);
Route::post('/submit-post',[PostController::class, 'store']);

Screenshots:

  • Screenshot 2021 11 17 at 11.34.01 PM
  • Screenshot 2021 11 17 at 11.34.13 PM
  • Screenshot 2021 11 17 at 11.34.24 PM

Related

Php Laravel laravelphprequest

Post navigation

Previous post
Next post

Related Posts

Php Laravel whereHas

Laravel whereHas in eloquent Model Example

October 2, 2022March 16, 2024

In this blog post, we’ll take a look at Laravel whereHas in eloquent Model Example and advantages. whereHas method is an important part of the Eloquent ORM. It allows you to add a constraint to a relationship query. whereHas method can be used to filter records based on a relationship….

Read More
Php How to Add Captcha, validate and refresh captcha in Laravel Form

How to Add Captcha, validate and refresh captcha in Laravel Form ?

March 10, 2022November 17, 2023

Captcha is used to enhance the security of form. By adding the Captcha in laravel form we can prevent attackers to submit the form using the automated scripts and it adds an extra layer of security. To add the captcha in laravel form we can use package mews/captcha, its easy…

Read More
Php How to Change Date Format in Json Response Laravel

How to Change Date Format in Json Response Laravel ?

July 9, 2022November 17, 2023

In json response we get different data format and to change date format in Json Response Laravel we need to make bit extra efforts to show correct date format. Laravel provides by default two timestamp created_at and updated_at, and there format are according to database format but sometimes we want…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version