Laravel 5 – Conditionally append variables

A few words before

I know that you can append variables to model arrays and json representations by using the protected $appends = ["your", "vars", "here"]; array. But imagine the following situation:

The situation

Our use case would be a fictional game or similiar:

Imagine that we have a User model that holds simple information about an (human) user, like the full name, address and so on.

Now, we also have a Faction model that represents the faction/origin/guild/… of this user.

The Faction model is eager-loaded when retrieving users, because the Faction name is wanted almost every time when displaying the user information.

A User also has DailyStatistics, which holds some information about their daily scores (simple points would be enough).

The Clue

Because I want to know the points of the a faction, which is the sum of the user points, I thought about appending a new variable totalPoints.

The getTotalPointsAttribute function would look like this:

function getTotalPointsAttribute(){
    return $this->users->sum->getTotalPoints();
}

The problem

Everytime when we retrieve a user now, the eager-loaded faction would also want to calculate the totalPoints attribute. That means, that we have a lot of overhead per user.

The question

Is there a way to avoid situations like this? Can I “conditionally” append variables? Are properties calculated when they are hidden?

I tried to wrap the totalPoints variable in a simple function, instead of an accessor instead. The problem is, that Frontend-Frameworks like VueJS would need access to the totalPoints variable (or to an endpoint to retrieve that value, but this solution is the least favorable).


Source: stackoverflow-php

Misunderstanding lifecycle hooks VueJS

I’m starting a tuto on the framework Vue.JS.

I m using the life cycle created of the Vue. I thought that this function was called once the vue is created. But in this example,
A behavior that I do not understand.

<template>
  
</template> export default { name: 'game', created: function () { console.log('On Vue created') document.onkeydown = this.start }, methods: { clickOnRound: function (event) { console.log('Click') }, bonus: function (event) { console.log('Click + alt') console.log(event) }, start: function (event) { console.log('Start called') console.log(event) } } }

When I type a letter on the keyboard, the function start is called, without calling the function of created.

Here the console output:

  • On Vue created
  • Start called
  • Start called
  • Start called
  • Start called

I can t understand how the start function is called without calling each time the created function , because the start function is inside the created function.

 created: function () {
      console.log('On Vue created')
      document.onkeydown = this.start
    },


Source: stackoverflow-javascript