Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KHAN's avatar
Level 4

Get entries with no relationship to user

Hi,

I have 3 tables. Users, Events and Reservations(rsvps).

I would like to return back all events where there are no reservation for user 1. Basically allowing user 1 to see all events he does not have a reservation for.

User Model

class User extends Authenticatable
{
    protected $with = [
        'events',
        'reservations',
    ];
    public function events() {
        return $this->hasMany('App\EventModel');
    }
    public function reservations() {
        return $this->hasMany('App\Rsvp');
    }
}

Event Model

class EventModel extends Model
{
    protected $table = 'events';

    protected $with = [
        'rsvps'
    ];  
    public function rsvps() 
    {
        return $this->hasMany('App\Rsvp', 'event_id');
    }
}

Resveration(rsvp)

class Rsvp extends Model
{
    public function user()
    {
        return $this->belongsTo('User');
    }
    public function event()
    {
        return $this->belongsTo('App\EventModel');
    }
}

I tried something like this.

$newEvents = EventModel::where('rsvps.user_id', '!=', 1)->get();

Events will have an rsvps array with multiple object entries because its a 1-to-many. So my above logic is a bit flawed. Any help?

0 likes
2 replies
SaeedPrez's avatar
Level 50

One way to do it is to get all the user's event Ids, then get all events where the event Id is not one of those Ids...

// Query relationship
$ids = $user->events->pluck('id');

// Or query pivot model
$ids = App\PivotModel::where('user_id', $userId)->pluck('event_id');

// Get events
$events = App\Event::whereNotIn($ids)->get();

PS. This is just an example code to give you an idea, modify it to fit your project and relationships..

KHAN's avatar
Level 4

@SaeedPrez

Thanks tweaked it a little to match my models and it worked :)

1 like

Please or to participate in this conversation.