Laravel model getting instances of the class -
i developing package in workbench environment. have model like
<?php namespace vendor\webshop\models; use vendor\webshop\models\country country; use illuminate\database\eloquent\model eloquent; /** * catalog */ class catalog extends eloquent { // define database protected $table = 'catalogs'; // mass assignment restriction protected $guarded = array('id'); // return countries related catalog public function countries() { return $this->belongstomany('vendor\webshop\models\country'); } /** * returns whether enforce compability check or not */ public function getforcecompabilitytest() { return $this->force_compability_check; } } ?>
i wondered if can have custom instance getters like
public function getdefaultcatalogs() { return catalog::where('is_default_catalog', '=', true)->get(); }}
within class itself. possible or methods available concrete instance, can call them catalog::getdefaultcatalogs()
outside of class?
laravel's eloquent support kind of behaviour - it's call "query scopes" http://laravel.com/docs/eloquent#query-scopes
in model, this:
class catalog extends eloquent { public function scopedefault($query) { return $query->where('is_default_catalog', '=', true); } }
then, can retrieve record call
$defaultcatalog = catalog::default()->get(); // or order them, if there more 1 default catalog. , on... $defaultcatalog = catalog::default()->orderby('created_at')->get();
Comments
Post a Comment