title: Custom Laravel Relations?
body: <p>Hypothetical situation: Let's say we have 3 models:</p>
  
  <ul>
  <li><code>User</code></li>
  <li><code>Role</code></li>
  <li><code>Permission</code></li>
  </ul>
  
  <p>Let's also say <code>User</code> has a many-to-many relation with <code>Role</code>, and <code>Role</code> has a many-to-many relation with <code>Permission</code>. </p>
  
  <p>So their models might look something like this. (I kept them brief on purpose.)</p>
  
  <pre><code>class User
  {
      public function roles() {
          return $this-&gt;belongsToMany(Role::class);
      }
  }
  
  class Role
  {
      public function users() {
          return $this-&gt;belongsToMany(User::class);
      }
  
      public function permissions() {
          return $this-&gt;belongsToMany(Permission::class);
      }
  }
  
  class Permission
  {
      public function roles() {
          return $this-&gt;belongsToMany(Role::class);
      }
  }
  </code></pre>
  
  <p><strong>What if you wanted to get all the <code>Permission</code>s for a <code>User</code>?</strong> There isn't a <code>BelongsToManyThrough</code>.</p>
  
  <p>It seems as though you are sort of stuck doing something that doesn't feel quite right and doesn't work with things like <code>User::with('permissions')</code> or <code>User::has('permissions')</code>.</p>
  
  <pre><code>class User
  {
      public function permissions() {
          $permissions = [];
          foreach ($this-&gt;roles as $role) {
              foreach ($role-&gt;permissions as $permission) {
                  $permissions = array_merge($permissions, $permission);
              }
          }
          return $permissions;
      }
  }
  </code></pre>
  
  <p>This example is, just one example, don't read too much into it. The point is, how can you define a <em>custom</em> relationship? Another example could be the relationship between a facebook comment and the author's mother. Weird, I know, but hopefully you get the idea. Custom Relationships. How?</p>
  
  <p>In my mind, a good solution would be for that relationship to be described in a similar way to how describe any other relationship in Laravel. Something that returns an Eloquent <code>Relation</code>.</p>
  
  <pre><code>class User
  {
      public function permissions() {
          return $this-&gt;customRelation(Permission::class, ...);
      }
  }
  </code></pre>
  
  <p><strong>Does something like this already exist?</strong></p>