Accessing distant relationships in laravel

Another really interesting Eloquent feature is the possibility to define (and then access) a distant relation, using the hasManyThrough() method.

What? I see you are a little confused. No problem: let’s take another example, which is a little different from our actual context.

Imagine that you are writing an application for some kind of research management for a research team. In this software, every user will be able to create a new research entity, and then add some sections to that research something like this:

  • A User entity that has a one-to-many relationship with a Research entity
  • The Research entity has a one-to-many relationship with a Section entity

Good. First of all, for models, you could write something like this:

  // file: app/User.php
  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class User extends Model {

    public function researches()
    {
      return $this->hasMany('AppResearch');
    }

  }

  // file: app/Research.php
  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Research extends Model {

    public function user()
    {
      return $this->belongsTo('AppUser');
    }

    public function sections()
    {
      return $this->hasMany('AppSection');
    }

  }

  // file: app/Section.php
  <?php namespace App;

  use IlluminateDatabaseEloquentModel;

  class Section extends Model {

    public function research()
    {
      return $this->belongsTo('AppResearch');
    }

  }


About the author

Deven Rathore

I'm Deven Rathore, a multidisciplinary & self-taught designer with 3 years of experience. I'm passionate about technology, music, coffee, traveling and everything visually stimulating. Constantly learning and experiencing new things.

Pin It on Pinterest

Shares