Update pages-field programatically

Is there a way to update a pages field programmatically?
I want to give users the opportunity to mark pages as their favourites in the frontend. The favourites should be saved in a pages field in the user’s profile via an AJAX-call to to a route.

$user->update([
  'favourites' => $conversation
]);

I’ve got this working as long as $conversation is a page object but not when I add a pages object.
And to make things even more complicated: How would I save the previous favourites in order to add to them?

This is my (messy) route:

'pattern' => '/conversation/favourite/(:any)',
        'action'  => function ($value) use ($kirby) {

          $data = Str::split($value, '+');
          $user = $kirby->user($data[0]);
          $conversation = $kirby->site()->find('conversations')->children()->findBy('uid', $data[1]);

          try {

            $user->update([
              'favourites' => $conversation
            ]);

            echo 'The user has been updated';
          } catch (Exception $e) {

            echo 'The user could not be updated';
            // optional reason: echo $e->getMessage();

          }
          return ' ';
        }

The pages field stores a list of page ids in this format:

pages:
- path/to/page
- path/to/another/page

So what you need to do, is read the original content into an array, using yaml(), then add any new items to this array, then store again as yaml encoded array.

Data::encode($array, 'yaml');
2 Likes

Ah, perfect. Would have never figured that out. Will give it a try tomorrow.
Thanks so much!

Thanks again @texnixe, I got this working really quickly this way. Just a note for future readers, I think the method needs to be yaml(), not toYaml().