1

I am trying to create a query scope which returns the first latest or null.

I created it like this:

public function scopeUpcomingAction()
{
    $upcomingAction = $this->actions()->latest()->whereNotNull('completed_at')->take(1);
    if ($upcomingAction->exists()) {
        return $upcomingAction;
    } else {
        return null;
    }
}

However when I use this scope like this:

    return $subject->load([
        'tasks' => function($query) {
            $query->with('upcomingAction');
        }
    ]);

when upcomingAction is null it gives me an empty array like this:

    {
        "id": 3,
        "created_at": "2018-01-13 19:08:30",
        "updated_at": "2018-01-13 19:08:30",
        "upcoming_action": []
    }

Can this be told to be singular?

Blagoh
  • 1,225
  • 1
  • 14
  • 29

1 Answers1

1

You're using a local scope as a relationship with the with() method. You can't do that. You should use a local scope like this:

Model::someScope()->get();

Loading a single latest record for hasMany() relation is pretty tricky. You need to create another relation and it must be hasOne().

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Oh my gosh thanks sooo much for the fast reply. I saw your live edits four times and each time I learned more. I'm going to click the link for the 4th edit now. Thanks very very much! I might have to try the hasOne thingy. – Blagoh Jan 13 '18 at 19:42
  • Alexey sorry to bother you, but I wasn't getting a good reply on this question here - https://stackoverflow.com/q/48259987/3791822 - I wanted to bring to your attention please in case you had any ideas, before I went ahead and tried this dangerous looking solution here - https://stackoverflow.com/q/43646085/3791822 - where a custom notification channel is created. – Blagoh Jan 19 '18 at 06:39
  • 1
    @Blagoh I saw the question and I can't help with it, sorry. – Alexey Mezenin Jan 19 '18 at 06:44
  • No problemo, thank you sir so much for the extensive extensive patience you had with me! :) – Blagoh Jan 20 '18 at 08:17
  • 1
    This solution of yours you linked to just came in handy again to me today. Thank you very much!!! – Blagoh May 04 '18 at 06:35