cosmoloc
cosmoloc

Reputation: 2994

Laravel eloquent : Model attribute with conditional concatenation

I have a table (say myreferencetable) with name list as..say :

id    |    name   |   abbrv
- - - - - - - - - - - - - - - - -
1     | ABCDEF    | abc
2     | TestState |
3     | UVWXYZ    | xyz

In my model I have created an attribute for the model :

protected $appends = [
        'full_name'
    ];

Now, I want to query DB such that I get the details as:

[
 { 
   "name" : ABCDEF
   "full_name" : ABCDEF (abc)
 },
 {
   "name" : TestState,
   "full_name" : TestState
 },
 {
   "name" : UVWXYZ,
   "full_name" : UVWXYZ (xyz)
 }
]

i.e. concatenation of strings :

Now, I have my query as :

public function getFullNameAttribute()
    {

        return  MyReferenceTable::select(DB::raw('concat(name," (", abbrv, ")")'));
    }

But it returns :

[
 { 
   "name" : ABCDEF
   "full_name" : {}
 },
 {
   "name" : TestState,
   "full_name" : {}
 },
 {
   "name" : UVWXYZ(xyz)
   "full_name" : {}
 }
]

I need to return name + ["(abbrv)"] // where [value] = if not null

Upvotes: 1

Views: 2242

Answers (4)

cosmoloc
cosmoloc

Reputation: 2994

Worked for :

 public function getFullNameAttribute()
        {
            return trim($this->name . (is_null($this->abbrv)? ""  : " (" . $this->abbrv . ")"));
        }

Upvotes: 0

pozs
pozs

Reputation: 36244

You could (ab)use the NULL-handling differences between the CONCAT() function and the concatenation operator ||, i.e.:

CONCAT(name, ' (' || abbrv || ')')

should do the trick.

Upvotes: 0

Nerea
Nerea

Reputation: 2157

Try this

public function getFullNameAttribute()
{
    if( ! $this->abbrv)
       return $this->name;

    return sprintf('%s (%s)', $this->name, $this->abbrv);

}

Upvotes: 0

Dmitry
Dmitry

Reputation: 2087

Try this method

public function getFullNameAttribute()
{
    return $this->name . ($this->abbrv ? ' (' . $this->abbrv . ')' : '');
}

Upvotes: 4

Related Questions