Profiles (limiting the output)

This is another useful tip, or not

You can limit the number of fields very easy. You don't want to have the whole record exposed when you send back an Ajax response.

For this you create in the root folder of a model (let's say User) a new folder named profiles.

In the former chapter we have seen the following:

public function cuser_info()
{
  return $this->hasOne(\Db\Eloquent\Models\User\profiles\Tiny::class, 'id', 'cuser');
}

So in the profiles folder you create a file named Tiny.php, or whatever you would like to call it.

Tiny.php

<?php

namespace Db\Eloquent\Models\User\profiles;

use Db\Eloquent\Models\User\Model as UserModel;

class Tiny extends UserModel
{
    protected $visible = [
        'id',
        'hash',
        'name',
        'surname',
        'fullname'
    ];
}

Appending fields to a model

Now let's focus on the fullname, this field is appended to the original User model. This is how it is done:


<?php
namespace Db\Eloquent\Models\User;

use Db\Eloquent\Models\User\Events as Events;
use Db\Eloquent\Models\Base\Model as BaseModel;

class Model extends BaseModel
{
    protected $table = 'users';
    protected $primaryKey = 'id';

    protected $fillable = [
        ...
    ];

    ...

    protected $appends = ['fullname'];

    ...

    public function getFullnameAttribute()
    {
        return trim($this->surname . ' ' . $this->name);
    }

    ...
}
Last update: Tue, 13 Sep 2022 14:32:15