Laravel 12 HTTP Requests: A Beginner’s Guide with Easy Examples
HTTP requests are the backbone of web applications. They allow users to interact with your app by sending data (like form submissions) and receiving responses. In Laravel, handling HTTP requests is simple and powerful.
In this guide, we’ll cover:
✅ Accessing Request Data
✅ Working with Input Values
✅ Handling File Uploads
✅ Managing Sessions & Cookies
✅ Trusting Proxies & Hosts
Let’s dive in! 🚀
1. Accessing the Request in Laravel
Laravel provides an easy way to access HTTP request data using the Illuminate\Http\Request class.
Method 1: Dependency Injection (Recommended)
Inject the Request object into your controller method:
use Illuminate\Http\Request;
public function store(Request $request) {
$name = $request->input('name'); // Get 'name' from request
return "Hello, $name!";
}
Method 2: Using the request() Helper
You can also use the global helper:
$name = request('name'); // Shortcut for $request->input('name')
Method 3: Dynamic Properties
Laravel allows dynamic property access:
$email = $request->email; // Same as $request->input('email')
2. Retrieving Input Data
You can fetch user-submitted data in multiple ways.
Getting All Input Data
$allInputs = $request->all(); // Returns all input data as an array
Getting a Specific Input
$username = $request->input('username'); // Get 'username'
$username = $request->username; // Alternative
Default Values if Input is Missing
$age = $request->input('age', 25); // Defaults to 25 if 'age' is missing
Checking if Input Exists
if ($request->has('email')) {
// Email field exists in the request
}
if ($request->filled('name')) {
// 'name' is present and not empty
}
3. Working with Files
Handling file uploads in Laravel is straightforward.
Retrieving an Uploaded File
$file = $request->file('photo'); // Get the uploaded file
Checking if a File Was Uploaded
if ($request->hasFile('photo')) {
// File was uploaded successfully
}
Storing Uploaded Files
$path = $request->file('photo')->store('images'); // Store in 'storage/app/images'
$path = $request->photo->storeAs('images', 'profile.jpg'); // Custom filename
4. Sessions & Flash Data
Sessions help store user data across requests.
Storing Data in Session
session(['user_id' => 1]); // Store a value
$userId = session('user_id'); // Retrieve it
Flash Data (One-Time Use)
Flash data is useful for success/error messages.
// Store flash data (available only in the next request)
session()->flash('message', 'Login successful!');
// Retrieve it (e.g., in Blade)
@if (session('message'))
<div class="alert">{{ session('message') }}</div>
@endif
5. Cookies in Laravel
Cookies store small data on the client side.
Retrieving a Cookie
$value = $request->cookie('name'); // Get cookie 'name'
Setting a Cookie
return response('Hello')->cookie('user', 'John', 60); // 60 minutes
6. Trusted Proxies & Hosts
If your app runs behind a load balancer (like AWS or Nginx), you need to configure trusted proxies.
Trusting All Proxies
// In bootstrap/app.php
$middleware->trustProxies(at: '*');
Trusting Specific Hosts
$middleware->trustHosts(at: ['laravel.test']);
Real-World Example: User Profile Update
Let’s build a simple profile update form.
1. Route & Controller
// routes/web.php
Route::put('/profile', [ProfileController::class, 'update']);
// ProfileController.php
public function update(Request $request) {
$request->validate([
'name' => 'required',
'avatar' => 'image|max:2048',
]);
$user = auth()->user();
$user->name = $request->name;
if ($request->hasFile('avatar')) {
$path = $request->file('avatar')->store('avatars');
$user->avatar = $path;
}
$user->save();
return back()->with('success', 'Profile updated!');
}
2. Blade Form
<form action="/profile" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<input type="text" name="name" value="{{ old('name', auth()->user()->name) }}">
<input type="file" name="avatar">
<button type="submit">Update</button>
</form>
@if (session('success'))
<div class="alert">{{ session('success') }}</div>
@endif
Final Thoughts
Laravel makes HTTP request handling effortless with:
✔ Simple data retrieval ($request->input(), $request->file())
✔ Session & cookie management (session(), cookie())
✔ File uploads (store(), storeAs())
✔ Security (Trusted proxies, validation)
Now you’re ready to build powerful web apps with Laravel! 🎉
Happy coding! 😊🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.