Laravel Model conditional formatting

余生颓废 提交于 2019-12-02 04:33:24

问题


I have a database and model called Vote_actions that looks like this:

  • id
  • group_id
  • user_id
  • action_type
  • anonymous (boolean)

User can ask to be anonymous (that would make the boolean value to be true).If that is the case, I want to change the group_id and user_id from the returned model to -1.

Is there a way in laravel that I can do it ?


回答1:


You are leaning towards an edge case, with special conditions.

Make use of accessors:

class VoteActions extends \Eloquent {

    public $casts = [
        'anonymous' => 'boolean'
    ];
    ...

    /**
    * Accessors: Group ID
    * @return int
    */
    public function getGroupIdAttribute()
    {
        if((bool)$this->anonymous === true) {
            return -1;
        } else {
            return $this->group_id;
        }
    }

    /**
    * Accessors: User ID
    * @return int
    */
    public function getUserIdAttribute()
    {
        if((bool)$this->anonymous === true) {
            return -1;
        } else {
            return $this->user_id;
        }        
    }
}

Official Documentation: https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

However, i would recommend that you set the value in the database directly to -1 where necessary so as to preserve the integrity of your application.




回答2:


Of course you can easily do that. Read about accessors (getters): https://laravel.com/docs/5.1/eloquent-mutators

Example:

function getUserIdAttribute()
{
    return $this->anonymous ? -1 : $this->user_id;
}

function getGroupIdAttribute()
{
    return $this->anonymous ? -1 : $this->group_id;
}



回答3:


I know this question is old. I was looking for a way to hide some fields on certain conditions, external conditions like Auth Roles, and internal conditions like Model attributes, and I found a very flexible way to hide them.

And since I saw the other OP's duplicated post Laravel Hidden Fields On Condition asking for hiding field instead, So I'm gonna share it with you.

I know a mutator can change the value of its field, but to Hide it, you need :

  1. the $hidden array attribute
  2. the constructor __Construct() (optional)
  3. to override method newFromBuilder method of Laravel Model

Here are the processes in the Model app\Vote_actions.php:

  1. Hidden. Let's say you normally want to hide the fields created_at and updated_at of Laravel, you use:

    protected $hidden = ['created_at', 'updated_at'];
    
  2. External Conditions. Now let's say if the Authenticated User is Staff you want to unhide them:

    public function __Construct()
    {
        parent::__construct();
    
        if(\Auth::check() && \Auth::user()->isStaff()) {
            // remove all fields so Staff can access everything for example
            $this->hidden = [];
        } else {
            // let's hide action_type for Guest for example
            $this->hidden = array_merge($this->hidden, ['action_type'];
        }
    }
    
  3. Internal Conditions Let's say now you want to hide anonymous field is its value is true:

    /**
     * Create a new model instance that is existing.
     *
     * @param  array  $attributes
     * @param  array  $connection
     * @return \Illuminate\Database\Eloquent\Model|static
     */
    public function newFromBuilder($attributes = array(), $connection = null)
    {
        $instance = parent::newFromBuilder($attributes, $connection);
    
        if((bool)$instance->anonymous === true) {
            // hide it if array was already empty
            // $instance->hidden = ['anonymous'];
    
            // OR BETTER hide single field with makeHidden method
            $instance->makeHidden('anonymous');
            // the opposite is makeVisible method
        }
    
        return $instance;
    }
    

You can't play with hidden attributes and method inside mutators, that's their weakness when we need to hide instead of changing values.

But in any case, understand that calling modification on high load of hundredths of rows can be costly in time.



来源:https://stackoverflow.com/questions/35908609/laravel-model-conditional-formatting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!