Support the ongoing development of Laravel.io →
Database Eloquent

Ok so I have a certifications table which can have many employees or materials. Also the employees and materials can have many different certifications. The docs say I need to call $certifications->employees or $certifications->materials. Is there a way I could just call some sort of catch-all method like $certification->certifiables that returns a single collection of employees and/or materials? Not sure if I am just looking at this the wrong way.

Here is my table structure: http://laravel.io/bin/68rYD

Last updated 2 years ago.
0

No, you can't do that. Laravel needs to know what to instantiate. Also Eloquent Collection relies on ids, so if you had the same ids for both morphed models, they would override one another.

Last updated 2 years ago.
0

Thanks jarektkaczyk, I was afraid that might be the case. Is there a better L4 way to handle this particular use-case then?

Last updated 2 years ago.
0

It depends on what you are trying to achieve.

For example you could convert to and merge base collections in order to work on all of the items:

$certificate = Certificate::find($id);

$materials = $certificate->materials->toBase();

$employees = $certificate->employees->toBase();

$certified = $materials->merge($employees);

// then you can do whatever you need:
$certified->sortBy('created_at');

$latest = $certified->filter(function ($item) {
  return $item->created_at > $someDate; 
});

$groupped = $certified->groupBy('SOME_COMMON_PROPERTY');

// and so on..
Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Robarelli robarelli Joined 14 Feb 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.