Skip to content

Instantly share code, notes, and snippets.

@RDelorier

RDelorier/HasOneScoped.php

Last active Feb 10, 2016
Embed
What would you like to do?
<?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

This comment has been minimized.

Copy link
Owner Author

@RDelorier RDelorier commented Feb 10, 2016

@antwaanvh

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