Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@danken00
Last active March 2, 2023 11:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danken00/3f30af1c700f29227985 to your computer and use it in GitHub Desktop.
Save danken00/3f30af1c700f29227985 to your computer and use it in GitHub Desktop.
Laravel 5 model casting function
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Collection as EloquentCollection;
use Illuminate\Database\Eloquent\Model as IlluminateModel;
use Illuminate\Pagination\AbstractPaginator;
class Model extends IlluminateModel
{
/**
* Casts a given array or collection to this model class if it isn't
* already
*
* @param mixed $results Collection/array/pagintor to cast
* @return mixed EloquentCollection or pagination object depending
* on what was passed in
*/
static function castResults($results)
{
// If the object being passed in is a paginator, let's create
// another paginator with the updated results
$isPaginator = is_a($results, AbstractPaginator::class);
$resultsToCast = $isPaginator ? $results->items() : $results;
// Item is an array. Check to make sure each item within that array
// is of the correct type, and cast if not
if (is_array($resultsToCast))
{
$castResults = new EloquentCollection();
foreach ($resultsToCast as $objectToCast)
{
if (!is_a($objectToCast, self::class))
{
$castResults->push((new static)->newFromBuilder($objectToCast));
}
else
{
$castResults->push($objectToCast);
}
}
}
else
{
$castResults = $resultsToCast;
}
// If the original object was a paginator, then re-create it as
// best we can
if ($isPaginator)
{
$paginatorClass = get_class($results);
$newPaginator = new $paginatorClass($castResults, $results->total(), $results->perPage(), $results->currentPage());
$newPaginator->setPath($results->resolveCurrentPath());
return $newPaginator;
}
else
{
return $castResults;
}
}
}
@haruntuncay
Copy link

thanks. it works well.

@Add1ctiv3
Copy link

Apart from changing a few class names which I suppose changed when the newer versions came, you sir are my personal hero!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment