Reputation: 5079
I am developing a package in the workbench environment. I have a model like
<?php namespace Vendor\Webshop\Models;
use Vendor\Webshop\Models\Country as Country;
use Illuminate\Database\Eloquent\Model as Eloquent;
/**
* A catalog
*/
class Catalog extends Eloquent {
// Define the database
protected $table = 'catalogs';
// Mass assignment restriction
protected $guarded = array('id');
// Return the countries related to this catalog
public function countries() {
return $this->belongsToMany('Vendor\Webshop\Models\Country');
}
/**
* Returns whether to enforce the compability check or not
*/
public function getForceCompabilityTest() {
return $this->force_compability_check;
}
}
?>
I wondered if i can have custom instance getters like
public function getDefaultCatalogs() {
return Catalog::where('is_default_catalog', '=', true)->get();
}}
within the class itself. Is this possible or are the methods only available to a concrete instance, can i call them like Catalog::getDefaultCatalogs()
from outside of the class?
Upvotes: 3
Views: 9536
Reputation: 22872
Laravel's Eloquent support this kind of behaviour - it's call "Query Scopes" http://laravel.com/docs/eloquent#query-scopes
In your model, to this:
class Catalog extends Eloquent {
public function scopeDefault($query)
{
return $query->where('is_default_catalog', '=', true);
}
}
Then, you can retrieve record with this call
$defaultCatalog = Catalog::default()->get();
// or even order them, if there are more than 1 default catalog. And so on...
$defaultCatalog = Catalog::default()->orderBy('created_at')->get();
Upvotes: 3
Reputation: 5079
I just added the method as a static method to the Eloquent model and it works fine. If anybody has comments on this, let me know.
public static function getDefaultCatalog() {
return Catalog::where('is_default_catalog', '=', true)->firstOrFail();
}}
Upvotes: 0