Skip to content

Instantly share code, notes, and snippets.

@danrichards
Last active August 27, 2016 23:35
Show Gist options
  • Save danrichards/ca8caf7e80342ddd529abf84915b5058 to your computer and use it in GitHub Desktop.
Save danrichards/ca8caf7e80342ddd529abf84915b5058 to your computer and use it in GitHub Desktop.
$queryProps property for Eloquent Model with example.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model as BaseModel;
/**
* Class Model
*/
abstract class Model extends BaseModel
{
/** @var array $queryProps */
protected $queryProps = [];
/**
* @param string $key
* @return mixed
*/
public function __get($key)
{
if (in_array($key, $this->queryProps)) {
return call_user_func([$this, $key])->get();
}
return parent::__get($key);
}
}
<?php
namespace App\Models;
use App\Model;
/**
* Here is some example file for usage
*/
class Store extends Model implements StoreInterface
{
/**
* @see \App\Model::__get
* @var array $queryProps */
protected $queryProps = [
'customers', // $store->customers = Eloquent Collection of Customer
'orders', // $store->orders = Eloquent Collection of Order
'listings', // $store->listing = Eloquent Collection of Listing
// Scope Queries may also be called this way
'visitable' // $store->visitable = Eloquent Collection of Store
];
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function customers()
{
// return Customer::select('customers.*')->where('...');
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function orders()
{
// return Order::select('orders.*')->where('...');
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function listings()
{
// return Listing::select('listings.*')->where('...');
}
/**
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeVisitable($query)
{
// return $query->whereNotNull('location_id');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment