Q:

With relation if not null

I have this select but I do not know how to GET only the registers that events are not null:
$getUsers = User::where('user_id', $userId)
    ->with(['events' => function($query) {
            $query->where('finnish', 0)
    ->orderBy('event_id', 'desc');
        }])
    ->get();

With this query I get this result, where user has not meet the where condition of the relation:
{
    "events": [
        {
            "user_id": 1,
            "event_id": 1,
            "created_at": null,
            "updated_at": null,
            "events": {
                "event_id": 1,
                "name": "test 1"
            }
        },
        {
            "user_id": 1,
            "event_id": 25,
            "created_at": null,
            "updated_at": null,
            "events": null
        },
        {
            "user_id": 1,
            "event_id": 34,
            "created_at": null,
            "updated_at": null,
            "events": null
        }
    ]
}

And I only like this:
{
    "events": [
        {
            "user_id": 1,
            "event_id": 1,
            "created_at": null,
            "updated_at": null,
            "events": {
                "event_id": 1,
                "name": "test 1"
        }
    ]
}

Thanks

A:

You can query relationship existence using ->has('events').
And if you want extra filters, there is whereHas.
$getUsers = User::where('user_id', $userId)
    ->whereHas('events', function function($query) {
        $query->where('finnish', 0);
    }
    ->with(['events' => function($query) {
        $query->where('finnish', 0)
            ->orderBy('event_id', 'desc');
    }])
    ->get();

