Laravel 12 HTTP Requests: A Beginner’s Guide with Easy Examples

Author

Kritim Yantra

Apr 02, 2025

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! 😊🚀

Tags

Laravel Php

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Continue with Google

Related Posts

How to Upload Images in Laravel 12: A Step-by-Step Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 Roles and Permissions Setup: Complete Guide
Kritim Yantra Kritim Yantra
Feb 28, 2025
Laravel 12 & AdminLTE Integration: Setup Your Stunning Admin Dashboard
Kritim Yantra Kritim Yantra
Feb 28, 2025