Mutator as Standard Attribute

Asked

Viewed 72 times

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 Collection via API and no longer have access to the properties of the object when I do this.


EDIT 1:

To simplify understanding:

Users have product, and the product has the sold_on_register.

I want to have access to the product attribute through the user, however, I will not do it in Lade to be able to use the mutator method, I need this attribute to be inserted by default.

Example:

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

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

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

1 answer

1


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

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');
    }
}

Utilizing:

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

Exit:

{
    "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 that this example is for 1:1 ratio as I might understand by your code, but, the strategy is always this, create a accessor then configure the appends.

References

Browser other questions tagged

You are not signed in. Login or sign up in order to post.