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

vincent15000's avatar

Serialization / deserialization

Hello,

I have this code.

public $users;

public function mount()
{
    $this->users = User::
        select('id', 'name')
        ->where('company_id', auth()->user()->company_id)
        ->orderBy('name')
        ->get();
}

When the component loads, all works fine, I have only the id and the name for each user.

But when I trigger an action, the page refreshed and for each user, I have all the fields (and not only the id and the name).

How can I avoid this problem ?

Thanks for your help.

V

0 likes
2 replies
LaryAI's avatar
Level 58

When you assign Eloquent models (like the result of User::select(...)->get()) directly to a public property in a Livewire component, Livewire will serialize and then rehydrate those models on every request. During this process, Livewire will re-query the database for each model using their primary key, and by default, it will fetch all columns, not just the ones you originally selected.

That's why after an action, you see all fields for each user, not just id and name.

Solution

Instead of passing Eloquent models directly to the public property, convert them to arrays with only the fields you want. You can do this using toArray() and map():

public $users;

public function mount()
{
    $this->users = User::select('id', 'name')
        ->where('company_id', auth()->user()->company_id)
        ->orderBy('name')
        ->get()
        ->map(function ($user) {
            return [
                'id' => $user->id,
                'name' => $user->name,
            ];
        })
        ->toArray();
}

Now, $this->users will be a simple array of arrays, and Livewire will not try to rehydrate Eloquent models, so only the id and name fields will be present.

Summary:

  • Don't store Eloquent models in public properties if you want to control which fields are present after serialization.
  • Store plain arrays instead.

Let me know if you need more details!

Please or to participate in this conversation.