cameronscott137
4 months ago

Handling Laravel Model Relationships within Vue

Posted 4 months ago by cameronscott137

In my Laravel/Vue applications, there are frequently scenarios where I need to build a component that functions both in the create/update contexts. For instance:

// Creating a new user
<user-form-component></user-form-component>

// Updating an existing user
<user-form-component :user="{{$user}}"></user-form-component>

In the component itself, I typically have to end up doing something like the following:

props: ['user'],
data() {
    return {
        userArray: this.user,
        userFollowers: (this.userArray === undefined ? [] : this.userArray.followers),
        userTopics: (this.userArray === undefined ? [] : this.userArray.topics)
    }
},

Where followers and topics are relations of the User object that I've eager-loaded. (This is just a simple example.)

This works, but using ternaries here looks ugly, ungraceful, and a bit difficult to understand at a glance.

How have you handled this scenario in the past? Can folks recommend another way to handle it?

Please sign in or create an account to participate in this conversation.