Skip to content

Instantly share code, notes, and snippets.

@g-p-c-s
Created February 11, 2017 18:32
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 g-p-c-s/f600ae01bc368f10b03e501bcb7a6ed6 to your computer and use it in GitHub Desktop.
Save g-p-c-s/f600ae01bc368f10b03e501bcb7a6ed6 to your computer and use it in GitHub Desktop.
Overriding Eloquent Model's constructor...
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* @version 1.0
*/
class CustomAttribute extends Model
{
private $attributeRanks;
public function __construct(array $attributes=[])
{
parent::__construct($attributes);
// Not sure if this makes things better
$this->attributeRanks = attribute_ranks();
}
public function rank()
{
return $this->attributeRanks->get($this->attribute, 99);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
/**
* @version 2.0
*/
class CustomAttribute extends Model
{
public function rank()
{
return attribute_ranks()->get($this->attribute, 99);
}
}
@g-p-c-s
Copy link
Author

g-p-c-s commented Feb 11, 2017

There was this requirement to sort a list of models before rendering in a view. There wasn't really any field that I could rely on to sort. So, added this logic into the model's constructor. Later changed it to a helper function and got rid of constructor overriding.

Suggestions are welcome.

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