Inverse of HasManyThrough relation is missing from Laravel's ORM. Belongs-To-Through extends Eloquent ORM with belongsToThrough relation.
Eloquent is awesome but it does have some problems. Checkout Plug!
Either PHP 5.6+ is required.
To get the latest version of Belongs-To-Through, simply require the project using Composer:
$ composer require znck/belongs-to-through
Instead, you may of course manually update your require block and run composer update
if you so choose:
{
"require": {
"znck/belongs-to-through": "^2.2"
}
}
Within your eloquent model class add following line
class User extends Model {
use \Znck\Eloquent\Traits\BelongsToThrough;
...
}
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\Traits\BelongsToThrough;
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\Traits\BelongsToThrough;
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\Traits\BelongsToThrough;
public function country() {
return $this->belongsToThrough(Country::class, [State::class, District::class]);
}
}
Please see CHANGELOG for more information what has changed recently.
$ composer test
Please see CONTRIBUTING and CONDUCT for details.
If you discover any security related issues, please email hi@znck.me instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.