Unit 4 - Notes

INT221 7 min read

Unit 4: URL Generation, Request Data and Emails

1. Request Data-Retrieval

In MVC frameworks like Laravel, handling HTTP requests is the primary method of interacting with user input. The Illuminate\Http\Request instance provides an object-oriented way to interact with the current HTTP request being handled by your application, including input, cookies, and files.

Accessing the Request

To obtain an instance of the current HTTP request via dependency injection, type-hint the Illuminate\Http\Request class on your controller method.

PHP
use Illuminate\Http\Request;

public function store(Request $request)
{
    $name = $request->input('name');
}

Retrieval Methods

  • all(): Retrieves all incoming request's input data as an array.
    PHP
        $input = $request->all();
        
  • input(): Retrieves a specific item regardless of whether it comes from the query string or the request payload (POST data).
    PHP
        $name = $request->input('name', 'Default Value'); // Supports default values
        
  • query(): Retrieves values specifically from the query string (GET parameters).
    PHP
        $page = $request->query('page');
        
  • boolean(): Returns true for inputs like "1", "true", "on", and "yes". Useful for checkbox handling.
    PHP
        $archived = $request->boolean('archived');
        
  • only() and except(): Retrieves a subset of the input data.
    PHP
        $data = $request->only(['username', 'password']);
        $data = $request->except(['credit_card']);
        

Dynamic Properties

You may also access user input using dynamic properties on the Request instance.

PHP
$name = $request->name;


2. Old Input

When a form fails validation, it is crucial to maintain the user's input so they do not have to re-type everything. Laravel allows you to keep input from one request during the next request.

Flashing Input

The flash method on the Request instance will flash the current input to the session so that it is available during the user's next request.

PHP
$request->flash();
$request->flashOnly(['username', 'email']);
$request->flashExcept('password');

Redirecting with Input:
Most often, flashing is done while redirecting to the previous page.

PHP
return redirect('form')->withInput();
return redirect('form')->withInput($request->except('password'));

Retrieving Old Input

To retrieve flashed input from the previous request, use the old method on the Request instance or the global helper old() within Blade templates.

In Blade Templates:

HTML
<input type="text" name="username" value="{{ old('username') }}">

If the "username" input exists in the flashed session data, it will be displayed; otherwise, it will be empty (or the second argument provided as a default).


3. Uploaded Files

Handling file uploads requires the form to have the attribute enctype="multipart/form-data".

Retrieving Files

You can retrieve uploaded files using the file method or dynamic properties. The method returns an instance of Illuminate\Http\UploadedFile, which extends the PHP SplFileInfo class.

PHP
$file = $request->file('photo');
// OR
$file = $request->photo;

Inspecting Files

  • hasFile(): Determines if a file is present on the request.
    PHP
        if ($request->hasFile('photo')) { ... }
        
  • isValid(): Verifies that there were no problems uploading the file.
    PHP
        if ($request->file('photo')->isValid()) { ... }
        
  • File Meta Data:
    PHP
        $path = $request->photo->path();
        $extension = $request->photo->extension();
        

Storing Files

To store an uploaded file, use the store method. It moves the file to one of your configured filesystems (e.g., local, Amazon S3).

PHP
// Stores in 'storage/app/images', generates a unique hash for filename
$path = $request->file('photo')->store('images');

// Stores with a specific filename
$path = $request->file('photo')->storeAs('images', 'filename.jpg');


4. Cookies

Retrieving Cookies

Cookies are retrieved from the Request instance.

PHP
$value = $request->cookie('name');

Attaching Cookies to Responses

Cookies are not set on the Request; they are attached to the Response sent back to the browser.

PHP
return response('Hello World')->cookie(
    'name', 'value', $minutes
);

Generating Cookie Instances

If you need to generate a cookie but are not ready to return a response yet, you can use the Cookie facade to queue it.

PHP
use Illuminate\Support\Facades\Cookie;

Cookie::queue('name', 'value', 60);

Encryption: By default, all cookies in Laravel are encrypted and signed. Clients cannot modify them. To disable this for specific cookies, add them to the $except array in the EncryptCookies middleware.


5. Sending Emails

Laravel provides a clean, simple API over the popular SwiftMailer (or Symfony Mailer in newer versions) library.

Mailables

Emails in Laravel are represented by "Mailable" classes. These are stored in the app/Mail directory.

Generating a Mailable:

BASH
php artisan make:mail OrderShipped

Writing the Mailable

A Mailable class typically contains a build method (or content and envelope methods in newer Laravel versions) to configure the email.

PHP
public function build()
{
    return $this->from('example@example.com')
                ->view('emails.orders.shipped')
                ->with(['orderName' => $this->order->name]);
}

Sending the Mail

Use the Mail facade to send the email.

PHP
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;

// Send to a specific user
Mail::to($request->user())->send(new OrderShipped($order));

// Send to an email address
Mail::to('test@example.com')->send(new OrderShipped($order));

Configuration

Mail configuration is located in config/mail.php and typically references .env variables:

  • MAIL_MAILER (smtp, log, array, etc.)
  • MAIL_HOST
  • MAIL_PORT
  • MAIL_USERNAME
  • MAIL_PASSWORD

6. Laravel Localization

Localization (L10n) allows applications to support multiple languages. Laravel's localization features provide a convenient way to retrieve strings in various languages.

Configuration

The default language is set in config/app.php via the locale key.

PHP
'locale' => 'en',
'fallback_locale' => 'en',

Language Files

Language strings are stored in the lang directory (or resources/lang in older versions). There are two methods:

  1. Short Keys (PHP Arrays): Used for structured keys.

    • Path: lang/en/messages.php
    • Content:
      PHP
              return [
                  'welcome' => 'Welcome to our application!',
              ];
              
    • Path: lang/es/messages.php
    • Content:
      PHP
              return [
                  'welcome' => '¡Bienvenido a nuestra aplicación!',
              ];
              
  2. JSON Strings: Used when the key is the default translation.

    • Path: lang/es.json
    • Content:
      JSON
              {
                  "I love programming.": "Me encanta programar."
              }
              

Retrieving Translation Strings

You can retrieve lines using the __ helper function or the @lang Blade directive.

Usage:

PHP
echo __('messages.welcome');
echo __('I love programming.'); // Looks for JSON key

In Blade:

HTML
{{ __('messages.welcome') }}
@lang('messages.welcome')

Parameters / Placeholders

You can define placeholders in translation strings.

  • Definition: 'welcome' => 'Welcome, :name',
  • Usage: echo __('messages.welcome', ['name' => 'John']);

Setting Locale at Runtime

PHP
use Illuminate\Support\Facades\App;

App::setLocale('es');


7. Laravel Sessions

HTTP is stateless. Sessions provide a way to store information about the user across multiple requests. Laravel supports various session backends (file, cookie, database, redis, memcached) accessed through a unified API.

Configuration

Defined in config/session.php. The default driver is file.

Accessing Session Data

There are two primary ways to work with session data: using the global session helper or via the Request instance.

Via Request Instance:

PHP
public function show(Request $request, $id)
{
    $value = $request->session()->get('key');
    $value = $request->session()->get('key', 'default');
}

Via Global Helper:

PHP
// Retrieve a piece of data
$value = session('key');

// Retrieve with default
$value = session('key', 'default');

// Retrieve all data
$data = session()->all();

Storing Session Data

Put:
To store data in the session:

PHP
// Via Request
$request->session()->put('key', 'value');

// Via Helper
session(['key' => 'value']);

Push:
Push a value onto an array session value:

PHP
$request->session()->push('user.teams', 'developers');

Flash Data:
Store items in the session only for the next request. Useful for status messages.

PHP
$request->session()->flash('status', 'Task was successful!');

  • reflash(): Keeps all flash data for another request.
  • keep(['key']): Keeps specific flash data.

Deleting Session Data

Forget:
Removes a specific piece of data from the session.

PHP
$request->session()->forget('key');
$request->session()->forget(['key1', 'key2']);

Pull:
Retrieves the value and deletes it from the session in one statement.

PHP
$value = $request->session()->pull('key', 'default');

Flush:
Removes all data from the session.

PHP
$request->session()->flush();

Regenerating Session ID

To prevent session fixation attacks, it is often necessary to regenerate the session ID (Laravel does this automatically during login).

PHP
$request->session()->regenerate();