Laravel 5 snippet - Has many through many.

A current project has a requirement that users can share their jobs with other users.

The dummy model is User→UserWhoHasSharedWithMe→Jobs

First up is joining the user to those who have shared with them.

The join table has unconventional names, because it’s joining the Users table back to itself.

Table 1. Table Schema of users_shared_with_users table




The following relationship will return a collection of users who have shared their details with me:

Returning all users who have chosen to share with me
public function UsersWhoHaveSharedWithMe(){
    return $this->belongsToMany(

After working on a hasManyThroughMany type setup, dropping back to eloquent joins provides a concise way to return all jobs belonging to other users that I can access.

Returning all jobs belonging to other users (who have chosen to share with me)
public function JobsSharedWithMe(){
    return $this->UsersWhoHaveSharedWithMe()->join('jobs', 'jobs.user_id','=','')->select('jobs.*');

There you have it - simple has many through many relationship.