Skip to content

Instantly share code, notes, and snippets.

@RDelorier
Last active February 10, 2016 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RDelorier/d84ab077e3fe488b0cb1 to your computer and use it in GitHub Desktop.
Save RDelorier/d84ab077e3fe488b0cb1 to your computer and use it in GitHub Desktop.
<?php
namespace App\Models;
use App\Models\Traits\HasScopedRelations;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasScopedRelations;
public function addresses()
{
return $this->hasMany('App\Models\Address');
}
public function primaryAddress()
{
return $this->hasOneScoped('App\Models\Address')->with(['type' => 'primary']);
}
}
<?php
namespace App\Models\Relations;
use Illuminate\Database\Eloquent\Relations\HasOne;
class HasOneScoped extends HasOne
{
protected $attributes = [];
public function addConstraints()
{
parent::addConstraints();
if(static::$constraints){
$this->query->where($this->attributes);
}
}
public function addEagerConstraints(array $models)
{
parent::addEagerConstraints($models);
$this->query->where($this->attributes);
}
public function create(array $attributes)
{
return parent::create(array_merge($attributes, $this->attributes));
}
/**
* Add attribute scope.
*
* @param $attributes
*
* @return $this
*/
public function with($attributes)
{
$this->attributes = $attributes;
$this->query->where($attributes);
return $this;
}
}
<?php
namespace App\Models\Traits;
use App\Models\Relations\HasOneScoped;
/**
* Trait HasScopedRelations can be added to an eloquent model to extend functionality
*/
trait HasScopedRelations
{
/**
* @param $related
* @param null $foreignKey
* @param null $localKey
*
* @return HasOneScoped
*/
public function hasOneScoped($related, $foreignKey = null, $localKey = null)
{
$foreignKey = $foreignKey ?: $this->getForeignKey();
$instance = new $related;
$localKey = $localKey ?: $this->getKeyName();
return new HasOneScoped($instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey);
}
}
@RDelorier
Copy link
Author

@antwaanvh

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment