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
1 Answer 1
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 ofselect *
: this can increase transfer speed (especially if your database server is not local).
Sources (on Stack Overflow):
url
column? \$\endgroup\$