How to create meta tags dynamically in Laravel?

by percy_bauch , in category: SEO , 6 days ago

How to create meta tags dynamically in Laravel?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

by dustin.green , 5 days ago

@percy_bauch 

Creating dynamic meta tags in a Laravel application can significantly enhance the SEO of your web pages. Here's a step-by-step guide to implementing dynamic meta tags in a Laravel project:

Step 1: Create a Model and Controller (if not already present)

Let's assume you have a Page model and corresponding PagesController. If you don't have these, you can create them using artisan commands:

1
2
php artisan make:model Page -m
php artisan make:controller PageController


Make sure to define the necessary fields in your migration and migrate the database:

1
2
3
4
5
6
7
8
Schema::create('pages', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->string('meta_description');
    $table->string('meta_keywords');
    // other fields
    $table->timestamps();
});


Run the migration:

1
php artisan migrate


Step 2: Fetch Meta Data in Controller

In your PagesController, fetch the meta data from the database and pass it to the view:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use AppModelsPage;

class PageController extends Controller
{
    public function show($slug)
    {
        $page = Page::where('slug', $slug)->firstOrFail();

        return view('pages.show', compact('page'));
    }
}


Step 3: Pass Meta Data to Blade Views

In your Blade views (e.g., resources/views/pages/show.blade.php), use the meta data variables:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="{{ $page->meta_description }}">
    <meta name="keywords" content="{{ $page->meta_keywords }}">
    <title>{{ $page->title }}</title>
    <!-- Other meta tags -->
</head>
<body>
    <!-- Your content here -->
</body>
</html>


Step 4: Ensure SEO Best Practices

Make sure that each page's meta tags are unique and relevant to the content of the page. You can achieve this by using fields that are specifically tailored to hold data for each page's SEO.

Step 5: Test and Validate

Once the implementation is complete, you should test and validate your meta tags to ensure they are functioning as expected. Use tools like Google Search Console or any other SEO auditing tool to confirm that your meta tags are being recognized correctly.


By following these steps, you can create dynamic meta tags that help search engines understand the content of each page better, ultimately enhancing your site's SEO performance.