2017-12-20 1 views
0

Ich habe folgende User-ModellLaravel Eloquent Modell, zurückkehren leere Daten für Spalte basierend auf dem Wert einer anderen Spalte

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

Wenn eloquent Abfragen verwendet wird, ist es eine Möglichkeit, automatisch leer mobile Daten zurück, wenn mobile_share gleich zu 0 in der Reihe?

+0

Eloquent Mutators kann das sein, wonach Sie suchen: https://laravel.com/docs/5.5/eloquent-mutators#defining-an-accessor – Amade

Antwort

2

Ja, accessor die Arbeit erledigt.

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

Dann einfach anrufen mit.

$user->mobile; 
-1

Ich habe eine Lösung, die Ihre Bedürfnisse erfüllen kann.
in Ihrem Modell, definieren einen Getter:

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

dies löst eine Ausnahme aus – Chay22

1

Nun, alle Antworten sollten funktionieren, aber Sie können es inline! :

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

Für eine detaillierte Erklärung:

Gang in Ihrer Funktion Getter $ Mobil erlaubt das aktuelle mobile Attribut zu erhalten, also im Grunde, wenn $ this-> mobile_share = 0 und ist dann nicht null! return the mobile, wenn nicht, null zurückgeben

Verwandte Themen