Sort files manually, but move one file to the front

Hi there!

On a subpage I have a list of image and video files that I want to loop through in my template. They should be sorted by manual order.

However, one of the images is the “front page” image (determined via a select field in the panel) and needs to be moved to the front of the list (and therefore taken out of the manually sorted order).

How would I go about that? If possible I would like to receive one sorted list of files, so I only need to use one loop.

Thank you!

Yes, you could use the not() method to skip that file first, then after you have done sorting, prepend the file to the collection using $files->prepend().

I’m afraid I don’t quite understand the prepend() method. What is the first “key” argument supposed to be?

Currently I have this as the first step:

$files = $page->files()->sortBy('sort', 'asc')->not($page->mainimg())

What would the next step be?

Should work like this:

if($file = $page->mainimg()->toFile()) {
  $allFiles = $files->prepend(0, $file);

That means I need to set up an extra loop for the prepending, right?

Edit: Just gave it a test, works like a charm, thank you. Here’s the complete code for future reference.

    $allfiles = $page->files()->sortBy('sort', 'asc')->not($page->mainimg());

    foreach ($mediafiles as $file) {
      if($file = $page->mainimg()->toFile()) {
        $allfiles = $allfiles->prepend(0, $file);

Edit 2019-04-23: The above code does not work when there are no other media files apart from the cover image. I am not sure, why I thought you need a loop. All you need is this:

  $mediafiles = $page->files()->sortBy('sort', 'asc')->not($page->mainimg());

  if($file = $page->mainimg()->toFile()) {
    $mediafiles = $mediafiles->prepend(0, $file);