All Projects → ajcastro → Eager Load Pivot Relations

ajcastro / Eager Load Pivot Relations

Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.

Projects that are alternatives of or similar to Eager Load Pivot Relations

Plans
Laravel Plans is a package for SaaS apps that need management over plans, features, subscriptions, events for plans or limited, countable features.
Stars: ✭ 326 (+143.28%)
Mutual labels:  eloquent, laravel, model
Schedule
Schedule is a package that helps tracking schedules for your models. If you have workers in a company, you can set schedules for them and see their availability though the time.
Stars: ✭ 155 (+15.67%)
Mutual labels:  eloquent, laravel, model
Rating
Laravel Eloquent Rating allows you to assign ratings to any model.
Stars: ✭ 175 (+30.6%)
Mutual labels:  eloquent, laravel, model
Elasticsearch
The missing elasticsearch ORM for Laravel, Lumen and Native php applications
Stars: ✭ 375 (+179.85%)
Mutual labels:  eloquent, laravel, model
Laravel Model Status
Easily add statuses to your models
Stars: ✭ 510 (+280.6%)
Mutual labels:  eloquent, laravel, model
Laravel Sluggable
An opinionated package to create slugs for Eloquent models
Stars: ✭ 831 (+520.15%)
Mutual labels:  eloquent, laravel, model
Befriended
Eloquent Befriended brings social media-like features like following, blocking and filtering content based on following or blocked models.
Stars: ✭ 596 (+344.78%)
Mutual labels:  eloquent, laravel, model
Guardian
Eloquent Guardian is a simple permissions system for your users. While there are many other packages for permissions, this one solves everything in the most eloquent way.
Stars: ✭ 121 (-9.7%)
Mutual labels:  eloquent, laravel, model
Eloquent Approval
Approval process for Laravel Eloquent models
Stars: ✭ 79 (-41.04%)
Mutual labels:  eloquent, laravel
Laravel Approvable
Easily add an approval process to any laravel model.
Stars: ✭ 79 (-41.04%)
Mutual labels:  eloquent, laravel
Laravel Nullable Fields
Handles saving empty fields as null for Eloquent models
Stars: ✭ 88 (-34.33%)
Mutual labels:  eloquent, laravel
Requent
A GraphQL like interface to map a request to eloquent query with data transformation for Laravel.
Stars: ✭ 78 (-41.79%)
Mutual labels:  eloquent, laravel
Laravel Schedulable
Schedule and unschedule eloquent models elegantly without cron jobs
Stars: ✭ 78 (-41.79%)
Mutual labels:  eloquent, laravel
Flattable
It helps you manage de-normalized tables
Stars: ✭ 81 (-39.55%)
Mutual labels:  eloquent, laravel
Laravel Lucene Search
Laravel 4.2, 5.* package for full-text search over Eloquent models based on ZF2 Lucene.
Stars: ✭ 75 (-44.03%)
Mutual labels:  eloquent, laravel
Laravel Likeable
Rate Eloquent models with Likes and Dislikes in Laravel. Development moved to Laravel Love package!
Stars: ✭ 95 (-29.1%)
Mutual labels:  eloquent, laravel
Sarala
Javascript library to communicate with RESTful API built following JSON API specification. inspired by Laravel’s Eloquent
Stars: ✭ 101 (-24.63%)
Mutual labels:  eloquent, laravel
Laravel Ownership
Laravel Ownership simplify management of Eloquent model's owner.
Stars: ✭ 71 (-47.01%)
Mutual labels:  eloquent, laravel
Laravel Prefixed Ids
Friendly prefixed IDs for Laravel models
Stars: ✭ 88 (-34.33%)
Mutual labels:  eloquent, laravel
Laravel Translatable
Making Eloquent models translatable
Stars: ✭ 1,390 (+937.31%)
Mutual labels:  eloquent, laravel

Laravel Eloquent: Eager Load Pivot Relations

Eager load pivot relations for Laravel Eloquent's BelongsToMany relation.
Medium Story: https://medium.com/@ajcastro29/laravel-eloquent-eager-load-pivot-relations-dba579f3fd3a

Installation

composer require ajcastro/eager-load-pivot-relations

Usage and Example

There are use-cases where in a pivot model has relations to be eager loaded. Example, in a procurement system, we have the following:

Tables

items
 - id
 - name

units
 - id
 - name (pc, box, etc...)

plans (annual procurement plan)
 - id

plan_item (pivot for plans and items)
 - id
 - plan_id
 - item_id
 - unit_id

Models

class Unit extends \Eloquent {
}

use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Item extends \Eloquent
{
    // Use the trait here to override eloquent builder.
    // It is used in this model because it is the relation model defined in
    // Plan::items() relation.
    use EagerLoadPivotTrait;

    public function plans()
    {
        return $this->belongsToMany('Plan', 'plan_item');
    }
}

class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->using('PlanItem')
            // make sure to include the necessary foreign key in this case the `unit_id`
            ->withPivot('unit_id', 'qty', 'price');
    }
}


// Pivot model
class PlanItem extends \Illuminate\Database\Eloquent\Relations\Pivot
{
    protected $table = 'plan_item';

    public function unit()
    {
        return $this->belongsTo('Unit');
    }
}

From the code above, plans and items has Many-to-Many relationship. Each item in a plan has a selected unit, unit of measurement. It also possible for other scenario that the pivot model will have other many relations.

Eager Loading Pivot Relations

Use keyword pivot in eager loading pivot models. So from the example above, the pivot model PlanItem can eager load the unit relation by doing this:

return Plan::with('items.pivot.unit')->get();

The resulting data structure will be:

image

You may also access other relations for example:

return Plan::with([
  'items.pivot.unit',
  'items.pivot.unit.someRelation',
  'items.pivot.anotherRelation',
  // It is also possible to eager load nested pivot models
  'items.pivot.unit.someBelongsToManyRelation.pivot.anotherRelationFromAnotherPivot',
])->get();

Custom Pivot Accessor

You can customize the "pivot accessor", so instead of using the keyword pivot, we can declare it as planItem. Just chain the as() method in the definition of the BelongsToMany relation.

class Plan extends \Eloquent
{
    public function items()
    {
        return $this->belongsToMany('Item', 'plan_item')
            ->withPivot('unit_id', 'qty', 'price')
            ->using('PlanItem')
            ->as('planItem');
    }
}

Make sure we also use the trait to our main model which is the Plan model, because the package needs to acess the belongsToMany relation (items relation) to recognize the used pivot acessor.

use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;

class Plan extends \Eloquent
{
    use EagerLoadPivotTrait;
}


So instead of using pivot, we can eager load it by defined pivot accessor planItem.

return Plan::with('items.planItem.unit')->get();
$plan = Plan::with('items.planItem.unit');

foreach ($plan->items as $item) {
    $unit = $item->planItem->unit;
    echo $unit->name;
}

Other Examples and Use-cases

https://github.com/ajcastro/eager-load-pivot-relations-examples

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].