Eager load model using with but giving it another name - Laravel 5.2 Eager load model using with but giving it another name - Laravel 5.2 laravel laravel

Eager load model using with but giving it another name - Laravel 5.2


This feature is currently not supported in any Laravel version. Your best bet is to duplicate your relations and name them according to your needs. E.g.:

class Post extends Model    public function documents() {        return $this->hasMany(Document::class);    }    public function products() {        return $this->hasMany(Document::class)            ->where('type', 'product'); // Scope the query, if necessary    }    public function categories() {        return $this->hasMany(Document::class)            ->where('type', 'category'); // Would a Document really be of type 'category', though? Looks like a code smell.    }}$postsWithAllDocs = Post::with('documents')->get();$postsWithProductsOnly = Post::with('products')->get(); // Only eager load Documents of type 'product'

On a side note, you mention that a Document can be a product or category, which logically doesn't seem to make much sense. Part of the issue could probably be resolved by rethinking the structure of your database and relations.


Eager loading tells "load also this relationship data", so next you can access subject->relation without further queries

if you want to rename the relationship maybe you should do it renaming the relationshp in the model, not in the eager loading

you can also bypass this by adding virtual attributes:

function getProductAttribute(){    return $this->document;}

leaving eager loading on original document

resulting in product attribute that is the same as document:

$subject->product === $subject->document


I asked myself the same question, and since I didn't find a satisfying answer online, here is what I did.I had:

$o->load('X');

but I wanted the $o object to have attribute Y with the value of X relation. Since I already had the Y relation defined for $o, I couldn't rename X to Y and finish the job. So I did

$o['Y'] = $o->X();

I know this is not the best solution, but it works for my case :)

Note: load and with produce exactly the same number of sql queries - you need to choose the one which is more appropriate for your situation.