2
\$\begingroup\$

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.

Middleware:

<?php
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())
 ->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}}">
 <meta name="description" content="{{$metadata->description}}">
@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: enter image description here

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

1 Answer 1

4
\$\begingroup\$

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

Toby Speight
87.1k14 gold badges104 silver badges322 bronze badges
answered Jun 21, 2022 at 10:11
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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