0

Using the with method, I do not see anything near, on the docs, as to what I want to accomplish. Possible?

// bars is a hasMany() association

public function getFoo($id, $fooId)
{
    return $this
        ->where('id', $id)
        ->where('fooId', $fooId)
        ->with([
            'one',
            'two',
            'bars' => function($queries) {
                foreach ($queries as $key => $query) {
                    $queries[$key]['extraKey'] = 'extraValue'; // extrakey can be any name I want it to be.
                    // $query['extraKey'] = "extraValue";
                }
            }
        ])
        ->first();
}

I'm following Vlad's answer how to loop and modify but I'm not seeing extraKey in the returned data.

Do I have perform this action in the controller? Seems messy if that's the only way. I thought I could so these actions within the model itself.

I expect to see:

foo->bars[0]->extrakey;
Dan
  • 5,140
  • 2
  • 15
  • 30
Sylar
  • 11,422
  • 25
  • 93
  • 166

1 Answers1

1

You could make use of accessors in your Bar model:

class Bar extends Model
{
    // ...

    public function getExtraKeyAttribute()
    {
        return 'extraValue';
    }

    // ...
}

Additionally, if you want to include this value in the toArray output, add it the protected $appends property of your model:

class Bar extends Model
{    
    protected $appends = ['extra_key'];
Dan
  • 5,140
  • 2
  • 15
  • 30
  • Ok... I expect to get back the value from the loop . – Sylar May 11 '20 at 09:56
  • 1
    Do you mean inside this loop `foreach ($queries as $key => $query)`? That's not possible. In this function you can access the [query builder to restrict](https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads) the eager-loaded relations for bars. At this point there isn't any data loaded yet. – Dan May 11 '20 at 12:04
  • Ok I'm no longer going this route but I do found your answer useful for other things so I'll upvote. Many thanks. – Sylar May 11 '20 at 13:46