How to Set Meta(Title,Description,Keywords) in Layout file in Laravel livewire

In Laravel, To set meta tags (title, description, and keywords) dynamically in a Laravel Livewire layout file, follow these steps:

Step 1. Define Meta Properties in the Livewire Component

To add title, description, and keywords properties to your Livewire component and set default values or dynamically update them in the component’s logic.

Example:


<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ExampleComponent extends Component
{
public $title = "This is Dynamic Title";
public $description = "This is description for the page.";
public $keywords = "These are keywords default, keywords";

public function render()
{
return view('livewire.example-component')
->layout('layouts.app', [
'title' => $this->title,
'description' => $this->description,
'keywords' => $this->keywords,
]);
}
}

2. Pass Meta Data to the Layout File

Use the layout() method to pass the meta data when rendering the component.

3. Update the Layout File

Modify your layout file (e.g., resources/views/layouts/app.blade.php) to include meta tags. Use @yield for dynamic values with sensible defaults.

Example:


<!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="{{ $description ?? 'Default description for the site' }}">
<meta name="keywords" content="{{ $keywords ?? 'default, keywords' }}">
<title>{{ $title ?? 'Default Title' }}</title>
</head>
<body>
{{ $slot }}
</body>
</html>

4. Set Meta Data Dynamically in the Component

You can update the meta data dynamically in the Livewire component logic.

Example:


public function mount($data)
{
$this->title = $data['title'] ?? "Dynamic Title";
$this->description = $data['description'] ?? "Dynamic Description";
$this->keywords = $data['keywords'] ?? "dynamic, keywords";
}

5. Optional: Use Blade Components for Meta Tags

To streamline meta tag management, create a Blade component for meta tags.

Create a MetaTags Component:


// resources/views/components/meta-tags.blade.php
<meta name="description" content="{{ $description }}">
<meta name="keywords" content="{{ $keywords }}">
<title>{{ $title }}</title>

Include in Layout:


<x-meta-tags :title="$title ?? 'Default Title'" :description="$description ?? 'Default Description'" :keywords="$keywords ?? 'default, keywords'" />

Result

When you render the Livewire component, the meta tags in your layout file will automatically update based on the values provided.

Leave a Comment