Titan
Titan

Reputation: 6040

Laravel Eloquent Model, return blank data for column based on value of another column

I have the following User model

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'company', 'mobile', 'mobile_share', 'dob', 'email', 'password', 'active'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function teams()
    {
        return $this->belongsToMany('App\Team', 'team_user', 'team_id', 'user_id');
    }
}

When using eloquent queries, is there a way to automatically return empty mobile data if mobile_share is equal to 0 in the row?

Upvotes: 1

Views: 944

Answers (3)

Mathieu Ferre
Mathieu Ferre

Reputation: 4412

Well, all the answers should work but you can inline it ! :

public function getMobileAttribute($mobile)
{
    return $this->mobile_share ? $mobile : null;
}

For a more detail explanation :

passing $mobile in your getter function allow to get the current mobile Attribute, so basically, if $this->mobile_share != 0 and is not null then return the mobile, if not, return null

Upvotes: 1

Chay22
Chay22

Reputation: 2894

Yes, accessor does the job.

public function getMobileAttribute()
{
    if ($this->mobile_share !== 0 && isset($this->attributes['mobile'])) {
        return $this->attributes['mobile'];
    }
}

Then just call it easily with.

$user->mobile;

Upvotes: 2

Gothiquo
Gothiquo

Reputation: 868

I have a solution that can fit your needs.
In your Model, define a getter:

public getMobileAttribute($value)
{
    if (!$this->mobile_share) {
        return null;
    }
    return $value;
}

Upvotes: -2

Related Questions