Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@liam-wiltshire
Last active February 19, 2017 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liam-wiltshire/e4a2b4ce57dc5768c87a7f68b9becbd5 to your computer and use it in GitHub Desktop.
Save liam-wiltshire/e4a2b4ce57dc5768c87a7f68b9becbd5 to your computer and use it in GitHub Desktop.
<?php
namespace App\Models;
use LogicException;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\Collection;
abstract class JitModel extends \Illuminate\Database\Eloquent\Model
{
protected $parentCollection = null;
/**
* Load a relationship based on the method provided
*
* @param string $method The method name to load
*
* @return mixed
*/
public function getRelationshipFromMethod($method)
{
$relations = $this->$method();
if ($this->parentCollection && count($this->parentCollection) > 1) {
$this->parentCollection->load($method);
}
if (!$relations instanceof Relation) {
throw new LogicException('Relationship method must return an object of type '
. 'Illuminate\Database\Eloquent\Relations\Relation');
}
return $this->relations[$method] = $relations->getResults();
}
/**
* Create a new Eloquent Collection instance.
*
* @param array $models Array of models to create collection from
*
* @return \Illuminate\Database\Eloquent\Collection
*/
public function newCollection(array $models = [])
{
$collection = new Collection($models);
foreach ($collection as &$model) {
$model->parentCollection = $collection;
}
return $collection;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment