3

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;
});
3
  • That's the query builder, not Eloquent. If you'd use Eloquent you could create an accessor Commented Jun 27, 2020 at 20:46
  • This is not an eloquent query, but a query using the query builder. If it was an eloquent query you would work directly with an Event model and you could add color to the visible array and define a getColorAttribute function on the model: laravel.com/docs/7.x/eloquent-mutators#defining-an-accessor What words 5 do you see? Commented Jun 27, 2020 at 20:48
  • I understand that I can use Accessors to access columns that already exist. But I also need to add the column color to the collection which does not exist in the database. Commented Jun 27, 2020 at 21:02

1 Answer 1

8

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I really learned a lot from this example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.