Skip to content

blomqvist/belongs-to-through

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

belongsToThrough

Adds belongsToThrough relation to laravel models

Installation

First, pull in the package through Composer.

"require": {
    "znck/belongs-to-through": "~2.0"
}

Usage

Within your eloquent model class add following line

class User extends Model {
    use \Znck\Eloquent\Relations\BelongsToThroughTrait;
    ...
}

Example:

Consider a blog application. In this app, a country can have many users and a user can have many articles. So, hasManyThrough provides easy way to access articles from a country.

class Country extends Model {
    use \Znck\Eloquent\Relations\BelongsToThroughTrait;
    
    public function articles () {
        return $this->hasManyThrough(Article::class, User::class);
    }
}

If we are accessing the country of the article, then we have to use $article->user->country.

Class Article extends Model {
    use \Znck\Eloquent\Relations\BelongsToThroughTrait;
    
    public function country() {
        return $this->belongsToThrough(Country::class, User::class);
    }
}

Now, the magic: $article->country

Going deeper, City -> District -> State -> Country

Class City extends Model {
	use \Znck\Eloquent\Relations\BelongsToThroughTrait;
	
	public function country() {
		return $this->belongsToThrough(Country::class, [State::class, District::class]);
	}
}

About

Adds belongsToThrough relation to laravel models

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%