Sunday, May 21, 2017

Slim illuminate/database call outside method in model

How to call define class outside in illuminate/database model here is my code Slim illuminate seting

//Slim Database define
$dbcontainer = new \Illuminate\Container\Container();
$dbcontainer['customClass'] = new \FormatPrice();

$capsule = new \Illuminate\Database\Capsule\Manager($dbcontainer);
$capsule->addConnection($container['settings']['db']);
$capsule->setAsGlobal();
$capsule->bootEloquent();



// Format Price Class
class FormatPrice{
    public function format($price){
        // Note this is example for real code we using another function to format the price
        return "$price" . " USD";
    }
}

How to using format function in Model

//Here model class example
use Illuminate\Database\Eloquent\Model;
class Product extends Model{
    protected $table = 'product';
    protected $primaryKey = 'id';

    protected $appends = ['price_format'];

    public function getPriceFormatAttribute(){
        // call function fomart($this->attributes['price']) here
        return CustomClass::format($this->attributes['price']);
    }
}

how to call custom class we define in Container ? Or any solution is great !



via Peter Jack

Advertisement