Created
February 11, 2017 18:32
-
-
Save g-p-c-s/f600ae01bc368f10b03e501bcb7a6ed6 to your computer and use it in GitHub Desktop.
Overriding Eloquent Model's constructor...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.