Laravel - Request
Laravel - Request
Section titled “Laravel - Request”Laravel’s Illuminate\Http\Request class provides an object-oriented way to interact with the current HTTP request being handled by your application. This includes retrieving input, cookies, files, and information about the request itself.
Accessing the Request
Section titled “Accessing the Request”To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller method or route closure. The incoming request instance will automatically be injected by the Laravel service container:
use Illuminate\Http\Request;
Route::get('/users', function (Request $request) { // Use $request instance});
// In a controller method:public function store(Request $request){ $name = $request->input('name'); // ...}Retrieving the Request Path, Host, and Method
Section titled “Retrieving the Request Path, Host, and Method”The Illuminate\Http\Request instance provides a variety of methods for examining the incoming HTTP request. Here are a few common ones:
- The
pathmethod returns the request’s path information. So, if the incoming request is targeted athttp://example.com/foo/bar, thepathmethod will returnfoo/bar. - The
ismethod allows you to verify that the incoming request path matches a given pattern. You may use the*character as a wildcard when utilizing this method. - The
urlmethod returns the full URL for the incoming request. - The
fullUrlmethod returns the full URL including the query string. - The
methodmethod returns the HTTP verb for the request (GET, POST, PUT, DELETE). - The
isMethodmethod checks if the HTTP verb matches a given string.
Example: Inspecting the Request URI
Section titled “Example: Inspecting the Request URI”Step 1: Execute the command below to create a new controller named RequestDemoController.
php artisan make:controller RequestDemoControllerStep 2: After successful execution, the console will show a message like ‘Controller created successfully.’.
Step 3: Add the following code to app/Http/Controllers/RequestDemoController.php:
app/Http/Controllers/RequestDemoController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class RequestDemoController extends Controller{ public function inspect(Request $request) { echo 'Path: ' . $request->path() . '<br>'; echo 'Is foo/* pattern match? ' . ($request->is('foo/*') ? 'Yes' : 'No') . '<br>'; echo 'Is bar/* pattern match? ' . ($request->is('bar/*') ? 'Yes' : 'No') . '<br>'; echo 'Full URL: ' . $request->fullUrl() . '<br>'; echo 'HTTP Method: ' . $request->method() . '<br>'; }}Step 4: Add the following route definition in your routes/web.php file.
routes/web.php
use App\Http\Controllers\RequestDemoController;
Route::get('/foo/bar/test', [RequestDemoController::class, 'inspect']);Step 5: Visit the following URL in your browser:
http://localhost:8000/foo/bar/test?name=John
Step 6: The output will display information about the request URI, similar to this:
Path: foo/bar/test
Is foo/* pattern match? Yes
Is bar/* pattern match? No
Full URL: http://localhost:8000/foo/bar/test?name=John
HTTP Method: GET
Retrieving Input
Section titled “Retrieving Input”You can retrieve all incoming request’s input data as an array using the all() method. However, you typically only need a subset of the input. You can access user input using a few simple methods, regardless of the HTTP verb used for the request.
Using the input() method:
Section titled “Using the input() method:”The input() method retrieves values from the request payload (query string or form data).
$name = $request->input('name');// You can provide a default value if the input is not present$role = $request->input('role', 'guest');Using dynamic properties:
Section titled “Using dynamic properties:”You can also access user input using dynamic properties on the Illuminate\Http\Request instance.
$name = $request->name;When working with forms that contain array inputs, use “dot” notation to access the array elements:
$name = $request->input('products.0.name');$names = $request->input('products.*.name');Example: User Registration Form Input
Section titled “Example: User Registration Form Input”Step 1: Create a registration form view at resources/views/auth/register.blade.php.
resources/views/auth/register.blade.php
<!DOCTYPE html><html><head> <title>User Registration</title></head><body> <h2>Register</h2> <form action="{{ url('/user/submit-registration') }}" method="POST"> @csrf <div> <label for="name">Name:</label> <input type="text" id="name" name="name" value="{{ old('name') }}"> </div> <div> <label for="username">Username:</label> <input type="text" id="username" name="username" value="{{ old('username') }}"> </div> <div> <label for="password">Password:</label> <input type="password" id="password" name="password"> </div> <button type="submit">Register</button> </form></body></html>Note the use of @csrf for CSRF protection and old('field_name') to repopulate the form on validation errors (though validation isn’t shown in this specific controller example, it’s good practice).
Step 2: Execute the command below to create a UserRegistrationController.
php artisan make:controller UserRegistrationControllerStep 3: Console output will confirm: ‘Controller created successfully.’.
Step 4: Copy the following code into app/Http/Controllers/UserRegistrationController.php.
app/Http/Controllers/UserRegistrationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserRegistrationController extends Controller{ public function showRegistrationForm() { return view('auth.register'); }
public function register(Request $request) { // Retrieve the name input field using input() method $name = $request->input('name'); echo 'Name: ' . htmlspecialchars($name) . '<br>';
// Retrieve the username input field using dynamic property $username = $request->username; echo 'Username: ' . htmlspecialchars($username) . '<br>';
// Retrieve the password input field $password = $request->input('password'); echo 'Password: Displaying password here is insecure. Hashed version would be stored.'; // In a real application, you would hash the password: // $hashedPassword = Hash::make($password); }}Step 5: Add the following routes in routes/web.php.
routes/web.php
use App\Http\Controllers\UserRegistrationController;
Route::get('/register-user', [UserRegistrationController::class, 'showRegistrationForm']);Route::post('/user/submit-registration', [UserRegistrationController::class, 'register']);Step 6: Visit http://localhost:8000/register-user in your browser. You will see the registration form.
Step 7: Fill in the details and click “Register”. The next page will display the input values you submitted, demonstrating how they were retrieved in the controller. For example: Name: John Doe, Username: johndoe, Password: Displaying password here is insecure. Hashed version would be stored.
For more details on handling requests, including file uploads, cookies, and other advanced features, consult the official Laravel documentation on HTTP Requests.