Mutator as Default Attribute

1

I have a mutator similar to this:

public function getLastTotalAttribute()
{
  return $this->produto->sold_on_register;
}

I want the last_total attribute to be automatically generated in the query, as well as the common attributes of $fillable .

I need to use the collection via API and I no longer have access to object properties when I do this.

EDIT 1:

To simplify understanding:

Users have product, and the product has sold_on_register.

I want to have access to the attribute of the product through the user, however, I will not do this on the blade in order to use the mutator method, I need this attribute to be inserted by default.

Example:

User::find(1) will have the common user attributes

User::find(1)->last_total will access the mutator attribute if I do this on the blade or controller.

I need the last_total to be included in the attributes, of course, in User::find(1) for the API.

    
asked by anonymous 21.03.2018 / 18:36

1 answer

1

To add a field the technique used is serialization . You really need to create a accessor as you yourself have created, but you need to tell your model more one setting:

protected $appends = ['last_total'];

A complete example:

Class User :

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = ['name', 'email', 'password'];
    protected $hidden = ['password', 'remember_token'];
    protected $appends = ['last_total']; // adicionando item na serialização

    public function product()
    {
        return $this->hasOne('App\Product', 'user_id', 'id');
    }

    public function getLastTotalAttribute()
    {
        return $this->product->name;
    }
}

Class Product :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['user_id', 'name' ];

    public function user()
    {
        return $this->belongsTo('App\User', 'user_id', 'id');
    }
}

Usage:

return \App\User::find(1);

Output:

{
    "id":1,
    "name":"user 1",
    "email":"[email protected]",
    "created_at":"2018-03-22 04:03:33",
    "updated_at":"2018-03-22 04:03:33",
    "last_total":"Product 1",
    "product":{ 
                  "id":1,
                  "user_id":1,
                  "name":"Product 1",
                  "updated_at":"2018-03-22 04:05:04",
                  "created_at":"2018-03-22 04:05:04"
              }
 }

Note This example is for a 1: 1 ratio as I could understand by its code, but, the strategy is always this, create a accessor then set appends .

22.03.2018 / 05:08