# Laravel 9 - Metadata creation using middleware?

I wrote a middleware for laravel that grabs the current metadata for the specific URL you visit.

How it works: we use the $request and compare the current URL: $request->getRequestUri() with the URL in the database table:

So a User visits e.g. /features/landing my code would display the metadata (keywords, description) for the /features/landing in the database.

Middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

{
/**
* Handle an incoming request.
*
* @param  \Illuminate\Http\Request  $request * @param \Closure$next
* @return mixed
*/
public function handle(Request $request, Closure$next)
{

$metadata = DB::table('seos') ->where('url', '=',$request->getRequestUri())
->first();

view()->share('metadata', $metadata); return$next($request); } }  how I call it in my web.php router (wrapped over all pages!): Route::middleware([CreateMetadata::class])->group(function () {  then I have a component meta.blade.php I call on all pages: @if(isset($metadata))
{{-- primary meta tags --}}
<title>{{$metadata->title}}</title> <meta name="title" content="{{$metadata->title}}">
@endif


Question: Is this a good practice? Are there better ways to implement this feature? Because if we look at the waterfall of the code execution this currently takes by FAR the biggest time on the website:

• Welcome to Code Review! Do you know if there are any indexes on the database table e.g. on the url column? May 16 at 16:24

# Redis

If you really need to use specific data and you don't have other ways to do it you can use Redis.

## Misc improvements

• (Not sure if this works with Laravel 9) You also should not save direct URL but instead route name with:
\Request::route()->getName()


This will allow you to change URL of your pages easily and not having to go in your database every time you change a URL.

• If you don't need every field from your app, use select title, description instead of select *: this can increase transfer speed (especially if your database server is not local).

Sources (on Stack Overflow):