0

I have a Team-model that has been used several places, and which returns the fields from the database in an API-endpoint.

It's currently accessed and returned like this:

$team = Team::find(1)
return $team;

I would like to add a calculated variable to that returned Collection. I imagined that I could add it to the constructor of the Model, and thereby get it with all the places where the Team-model is currently used, like this:

class Team extends Model
{

    protected $table = 'teams';
    protected $fillable = [
        'id',
        'created_at',
        'updated_at',
        'team_name'
    ];

    public $number_of_players;

    public function __construct( array $attributes = [] ){
        $this->number_of_players = 3; //This number should be calculated
        parent::__construct( $attributes );
    }
}

But that doesn't work. How do I add a variable to all the places, where the Team-model is fetched?

I also looked into API Resources. I looks like that that could be a solution, but I found it pretty verbose and a long-haired solution (plus, I couldn't get it to work either).

Zeth
  • 2,273
  • 4
  • 43
  • 91
  • How about just using a custom method on the model which will return your calculated result. This way you will be able to use the method on the model anywhere you want. – guttume Sep 23 '19 at 09:33
  • why don't u use helper ? – Ripon Uddin Sep 23 '19 at 09:40
  • @guttume - If I add a custom method, then would I need to call `Team::with( 'number_of_players')->find( 1 )`, everywhere that the Team-model was accessed? It's this whole 'having-to-go-through-all-places-the-model-is-called', that I would like to avoid. – Zeth Sep 23 '19 at 09:58
  • @RiponUddin - How would I do that? – Zeth Sep 23 '19 at 09:58
  • @Zeth You can set `with` property on model to eager load on every request. ` /** * The relations to eager load on every query. * * @var array */ protected $with = []; ` – guttume Sep 23 '19 at 12:20

1 Answers1

2

You can use accessor/mutator

Suppose you have a relationship

Team->Player (Team hasMany Players)

You can do like

in Team model

class Model extends Model {
    public function players()
    {
        return $this->hasMany(Player::class, 'team_id', 'id');
    }
}

now you can make it

<?php
class Model extends Model {
    protected $appends = ['number_of_players'];

    public function players()
    {
        return $this->hasMany(Player::class, 'team_id', 'id');
    }

    public function getNumberOfPlayersAttribute()
    {
        return $this->players->count();
    }
}

And then access the players count of a team like App/Team::find(1)->number_of_players

Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105