Adding custom column to Eloquent query result (Laravel)

Viewed 3704

I get a collection from my database with

$events = DB::table('events')
  ->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
  ->get();

and want to add a field color so that I can set the color value depending on the value of the field title. My approach does not work, the echo and put gives an error.

$events->put('color', 'blue');
$events->each(function($item, $key){
  if($item == 'Garage')
    echo $item;
});
1 Answers

First use an Eloquent approach.

$events = Event::query()
    ->select('id', 'eventId', 'resourceId', 'title', 'start', 'end')
    ->get();

On your Event model, add an Eloquent accessor.

class Event extends Model
{
    public function getColorAttribute($value)
    {
        if ($this->title === 'Garage') {
            return 'blue';
        }

        return 'unknown';
    }
}

Now you can append this for transformation or access it directly.

class Event extends Model
{
     protected $appends = ['color'];
}

$event->color;
Related