Skip to content

Instantly share code, notes, and snippets.

@sngrl
Created December 6, 2018 17:27
Show Gist options
  • Save sngrl/b9be44ed2dad1a50e7b89b186b546a48 to your computer and use it in GitHub Desktop.
Save sngrl/b9be44ed2dad1a50e7b89b186b546a48 to your computer and use it in GitHub Desktop.
Laravel SleepingOwlAdmin - Orderable trait with additional scope
<?php
namespace Admin\Models\Traits;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use SleepingOwl\Admin\Traits\OrderableModel;
/**
* Trait OrderableModel.
* @method static $this orderModel()
* @method Builder findByPosition($position)
*/
trait ProductOrderTrait
{
use OrderableModel;
/**
* Move model up.
*/
public function moveUp()
{
if ($this->getOrderValue() > 1) {
$this->move(1);
}
}
/**
* Move model down.
*/
public function moveDown()
{
if ($this->getOrderValue() < static::orderModel()->count()) {
$this->move(-1);
}
}
/**
* Update order field on create.
*/
protected function updateOrderFieldOnCreate()
{
$this->{$this->getOrderField()} = static::orderModel()->count()+1;
}
/**
* Update order field on restore.
*/
protected function updateOrderFieldOnRestore()
{
static::orderModel()
->where($this->getOrderField(), '>=', $this->getOrderValue())
->increment( $this->getOrderField() );
}
/**
* REWRITE Order scope From ORDER Trait.
*
* @param $query
*
* @return mixed
*/
public function scopeOrderModel($query)
{
return $query->where($this->getParentFieldName(), $this->{$this->getParentFieldName()})
->orderBy( $this->getOrderField() );
}
/**
* Get order field name.
* @return string
*/
public function getOrderField()
{
return $this->orderField;
}
/**
* Get parent field name.
* @return string
*/
public function getParentFieldName()
{
return $this->parentFieldName;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment