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?

1 Answer 1

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().

Sign up to request clarification or add additional context in comments.

5 Comments

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.
Alexey sorry to bother you, but I wasn't getting a good reply on this question here - 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 - stackoverflow.com/q/43646085/3791822 - where a custom notification channel is created.
@Blagoh I saw the question and I can't help with it, sorry.
No problemo, thank you sir so much for the extensive extensive patience you had with me! :)
This solution of yours you linked to just came in handy again to me today. Thank you very much!!!

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.