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;
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:
url
column? \$\endgroup\$