Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model conditional formatting

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 ?

like image 696
harveyslash Avatar asked Jan 02 '26 03:01

harveyslash


1 Answers

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.

like image 81
Mysteryos Avatar answered Jan 03 '26 16:01

Mysteryos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!