Guest User

Untitled

a guest
Mar 22nd, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Traits;
  4.  
  5.  
  6. use Illuminate\Database\Eloquent\Relations\Relation;
  7.  
  8. trait HasManyThroughable
  9. {
  10. /**
  11. * This trait allows for a HasMany relationship through a polymorphic intermediate relationship.
  12. *
  13. * @param string $related The related class
  14. * @param string $through The intermediate class
  15. * @param string $morphName The name of the morphed entity
  16. * @param null|string $relationship The intermediate relationship
  17. * @param null|string $morphId
  18. * @param null|string $morphType
  19. * @param null|string $morphTypeMap
  20. *
  21. * @return mixed
  22. */
  23. public function hasManyThroughable($related, $through, $morphName, $relationship = null, $morphId = null, $morphType = null, $morphTypeMap = null)
  24. {
  25. $through = new $through();
  26.  
  27. $morphId = $morphId ?: $morphName . '_id';
  28.  
  29. $morphType = $morphType ?: $morphName . '_type';
  30.  
  31. if ($morphTypeMap === null) {
  32. if (! $morphTypeMap = array_search(get_class($through), Relation::morphMap(), false)) {
  33. $morphTypeMap = get_class($through);
  34. }
  35. }
  36.  
  37. $relationship = $relationship ?: camel_case(str_plural(class_basename($through)));
  38.  
  39. $throughIds = $this->$relationship->pluck($through->getKeyName());
  40.  
  41.  
  42. return $related::where($morphType, $morphTypeMap)->whereIn($morphId, $throughIds)->get();
  43. }
  44. }
Add Comment
Please, Sign In to add comment