Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ethump's avatar
Level 1

LIvewire preserving variable

Hi... got a problem but I think it's my lack of understanding.

I have a database of Things. Users of my app can add comments to Things. The comment adding part is just a livewire bound text box with a submit button. I want all the added comments for that Thing to be displayed under the text box. The list of comments should be updated in real time after a new comment is added - Livewire style!

The main controller passes $thing['id'] to the livewire component which looks like this:

public string $comment;

public $thing;

public function addComment()
{
    Comments::create(['
        'artefact' => $this->thing,'
        'user_id' => Session::get('userid'),
        'text' => $this->comment,

    ]);

    $this->reset();
}

public function render()
{
    return view('livewire.thing-comments', [
        'comments' => Comments::where('artefact', $this->thing)->orderBy('created_at', 'DESC')->get(),
    ]);
}

The blade component just foreaches through comments after the text box.

What's happening is that as soon as a new comment is entered, the entry goes into the database but the comment list comes back empty. It appears correct if I refresh the whole page (F5). The problem seems to be that $this->thing is now no longer defined when render() is called again, thus the search returns nothing.

If I hard code the Thing ID into the query at the end, it behaves as required (obviously though it's bound to the one thing).

How can I make Thing persist?

0 likes
4 replies
ethump's avatar
Level 1

I'm looking at: https://livewire.laravel.com/docs/session-properties

It seems to be what I need. But I can't get it working!

I added this:

use Livewire\Attributes\Session as lwSession;

(added the as lwSession since I'm using the Illuminate Session facade also.)

Preceeding the public $thing, I added:

#[Session].

Now it doesn't list any comments!

webrobert's avatar
webrobert
Best Answer
Level 51

Don’t reset everything.

$this->reset();

Just reset the comment.

ethump's avatar
Level 1

Brilliant! That's got it. Working exactly as I want now. Thanks much!

1 like
webrobert's avatar

@ethump, awesome. Kindly mark my answer as best reply to close the thread.

1 like

Please or to participate in this conversation.