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: