Search code examples
laravel-livewire

How to render Title attribute dynamically in Livewire


Below is my ShowPost component and I'd like the Title attribute to be dynamic depending on the post title instead of hard coding 'Laravel Roadmap'. Passing 'title' => $post->title in the blade template it doesn't work too. How can I make this dynamic?

<?php

namespace App\Livewire\Posts;

use App\Models\Post;
use Livewire\Attributes\Title;
use Livewire\Component;

class ShowPost extends Component
{
    public $post;

    public function mount(Post $post)
    {
        $this->post = $post;
    }

    #[Title('Laravel Roadmap')]
    public function render()
    {
        return view('livewire.posts.show-post', [
            'post' => $this->post,
        ]);
    }
}

Solution

  • You can specify the title using the title() method chained to the view() helper:

    public function render()
    {
        $dynamicTitle = "Ok, this isn't really dynamic but you get the idea";
    
        return view('livewire.posts.show-post', [
            'post' => $this->post,
        ])->title($dynamicTitle);
    }