Public property with scoped relation doesn't persist between requests

What seems to be the problem:

I used this great article (https://reinink.ca/articles/dynamic-relationships-in-laravel-using-subqueries) to help me include the single latest relation.

It uses a scope query on my model. That works absolutely fine, but when I submit my form the public property seems to lose the scoped relation but everything else persists.

Steps to Reproduce:

Are you using the latest version of Livewire:

^1.0

Do you have any screenshots or code examples:

public function updatedToTank()
{
    $this->transit = 
        Tank::withLastEvent()
            ->with('site')
            ->identifier($this->toTank)
            ->site($this->site()->id)
            ->first();
}

when the toTank field changes I fetch the relevant model, this works well because it only runs after my validateOnly call is successful in the main updated method.

But when I submit the form which is a new Livewire request, then try to access transit->lastEvent it is null in my submit handler method, so the scoped relation isn’t persisted.

I should note that the normal with(‘site’) works fine, I can access transit->site inside the submit handler.

Can anyone help or has anyone seen this before? Many thanks.

This is likely happening because javascript cannot read PHP objects. When livewire exposes your public variables after refresh, it needs to cast them as something javascript can read: string, int, array, etc. That’s why some of the accessors will work: $transit->site might be a string but $transit->lastEvent might be a model which javascript cannot work with. You’ll likely have to rethink how you’re passing information based on this. Loading $transit as an array that javascript can read with the information that you need would be one way of accomplishing this. Another might be to have a nested component access the lastEvent based on an id.

Hi, thanks for your response.

Sorry but I don’t think that’s quite right - $transit->site is an Eloquent model and it is persisted. When I dd $transit it has a relations member which contains site, and is also where lastEvent is null.

Also from the docs: “Properties can ONLY be either a JavaScript-friendly data types (string , int , array , boolean), OR an eloquent model (or collection of models).”