Rubyで言うところの rack-dev-mark 的なものをLaravelで実装したメモ。 パッケージもいくつか見つかるけどサクッと実装できてカスタマイズもしやすいので自前でやってみた。
具体的には以下のようなミドルウェアを書いてwebなルートに適用すれば良い。
namespace App\Http\Middleware;
use Closure;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
use Illuminate\Http\Request;
class DevMark extends Middleware
{
public function handle($request, Closure $next)
{
if (app()->isProduction()) {
return $next($request);
}
$response = $next($request);
$this->modifyResponse($response);
return $response;
}
private function modifyResponse(mixed $response): void
{
$content = $response->getContent();
$env = strtoupper($this->app['env']);
$renderedContent = <<<HTML
<style>
#devmark {
left: 10px;
top: 10px;
position: fixed;
padding: 5px 8px;
z-index: 100;
background-color: green;
color: white;
border-radius: 0.5rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: 900;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.3);
}
</style>
<div id="devmark" onclick="this.style.display = 'none';">{$env}</div>
HTML;
$pos = strripos($content, '</body>');
if ($pos !== false) {
$content = substr($content, 0, $pos) . $renderedContent . substr($content, $pos);
} else {
$content = $content . $renderedContent;
}
$response->setContent($content);
$response->headers->remove('Content-Length');
}
}
こんな感じで表示されてクリックすると非表示になる。

あとは環境ごとに色を変えてみたりすればOK。 ちなみに laravel-debugbar とかも 同じような仕組み で動いていたりする。