iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🌿

A Curious Way to Rewrite Data Passed to Laravel Views via Middleware

に公開
2025/01/15

Introduction

Knowing this might not be useful at all, but this time, I'm going to try rewriting values passed to a Laravel View using Middleware.

Environment

  • PHP 8.2.6
  • Laravel 10.13.5

Preparation

I'll prepare a simple process to pass values to a View and a blade template.

routes/web.php
  use Illuminate\Support\Facades\Route;

  Route::get('/', function () {
      return view('user', ['user' => ['name' => '太郎']]);
  });
resources/views/user.blade.php
名前は {{ $user['name'] }} です。

For now, I'll start the server with php artisan serve to check.

Implementation

Create Middleware

First, create a suitable Middleware using the command.

$ php artisan make:middleware ReplaceViewData

   INFO  Middleware [app/Http/Middleware/ReplaceViewData.php] created successfully. 

Register Middleware in the route

Once created, change the content of routes/web.php as follows.

routes/web.php
  use App\Http\Middleware\ReplaceViewData;
  use Illuminate\Support\Facades\Route;

  Route::get('/', function () {
      return view('user', ['user' => ['name' => '太郎']]);
+ })->middleware(ReplaceViewData::class);
- });

Middleware Implementation

Now, here is the implementation of the ReplaceViewData Middleware.
I'll explain what it does later, but first, here's the code!!

app/Http/Middleware/ReplaceViewData.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class ReplaceViewData
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        // 1. Assuming \Illuminate\Http\Response
        if ($response instanceof \Illuminate\Http\Response) {
                $original = $response->original;
        
                // 2. Since the type of the original property is mixed, check if it's an instance of \Illuminate\View\View
                if ($original instanceof \Illuminate\View\View) {
                    // 3. Get the values passed to the View and rewrite them
                    $data = $original->getData();
                    $user = $data['user'];
                    $user['name'] = '花子';
                    $original->with('user', $user);

                    // 4. Rewrite the value being passed to the response class
                    $response->setContent($original);
                }
        }
        
        return $response;
    }
}

What is being done in the Middleware

I will explain what is being done in order.

1. Assuming \Illuminate\Http\Response

The response is expected to be one of the following three types of classes (there might be others, but...):

  • \Illuminate\Http\Response
  • \Illuminate\Http\JsonResponse
  • \Illuminate\Http\RedirectResponse

So this time, we only consider \Illuminate\Http\Response.
We are not taking \Illuminate\Http\JsonResponse or \Illuminate\Http\RedirectResponse into account.

2. Since the type of the original property is mixed, check if it's an instance of \Illuminate\View\View

The value returned by the response is stored in the $original property of \Illuminate\Http\ResponseTrait (the trait used by \Illuminate\Http\Response).
Since it's a response, various types such as string, int, etc., can be expected.

So, since we want to rewrite the values passed to the View this time, we need to check if it's an instance of \Illuminate\View\View.

3. Get the values passed to the View and rewrite them

The values passed to the View can be obtained using the getData method of \Illuminate\View\View.
I'll just change the value of name as a simple processing.
To pass the rewritten values back to the View, use the with method.

4. Rewrite the values being passed to the response class

Just rewriting the values passed to the View will not be reflected in the response values, so it's necessary to set the values in \Illuminate\Http\Response again.

Since the $original property is public, it's possible to set the value directly, but what is ultimately returned is the $content property of Symfony\Component\HttpFoundation\Response, so setting a value in the $original property is meaningless.

Therefore, by using the setContent method, which is also called when an instance of \Illuminate\Http\Response is created, I am setting the value in the $content property as well.

Confirmation

Now, let's start the server again with php artisan serve to check.

Taro has successfully changed to Hanako.

Summary

There might be almost no opportunity to actually rewrite values passed to a View, but it was possible to easily rewrite them by using a Middleware class.

Discovering that such a thing is possible is the main takeaway this time.

GitHubで編集を提案

Discussion