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: enter image description here

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



namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CreateMetadata
     * 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())

        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:

    {{-- primary meta tags --}}
    <meta name="title" content="{{$metadata->title}}">
    <meta name="description" content="{{$metadata->description}}">

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: enter image description here

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

1 Answer 1



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:

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):


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.