I have the following problem when using mutators to be able to generate a value that is inserted into the database:
My model has a field called order
responsible for carrying the position of a menu, when I generate a new menu I want you to see max('order')
and increase +1
.
Mutator
public function setOrderAttribute($value)
{
$query = $this->where('parent', '0')->max('order');
$this->attributes['order'] = $query + 1;
}
Note: I tried doing another mutator with Name and if it worked, only when I manage whole does not add the value I need, I also tried with
$this->attributes['order'] = 20;
and nothing.
What am I doing wrong?
Greetings
UPDATE: The model
class Menu extends Model
{
use SoftDeletes;
use Sluggable;
protected $table = 'int_menu';
protected $primaryKey = 'id_menu';
protected $dates = ['deleted_at'];
protected $fillable = ['nombre', 'icono', 'parent', 'order', 'id_page'];
protected $casts = ['order' => 'integer'];
public function page()
{
return $this->belongsTo('App\Model\Intranet\Page' ,'id_page');
}
public function getChildren($data, $line)
{
$children = [];
foreach ($data as $line1) {
if($line['id_menu'] == $line1['parent']) {
$children = array_merge($children,
[array_merge($line1,
['submenu' => $this->getChildren($data, $line1)
])
]);
}
}
return $children;
}
public function optionsMenu()
{
return $this->where('enabled', 1)
->orderby('parent')
->orderby('order')
->orderby('nombre')
->get()
->toArray();
}
public static function menus()
{
$menus = new Menu();
$data = $menus->optionsMenu();
$menuAll = [];
foreach ($data as $line) {
$item = [ array_merge($line, ['submenu' => $menus->getChildren($data, $line) ]) ];
$menuAll = array_merge($menuAll, $item);
}
return $menus->menuAll = $menuAll;
}
public function setOrderAttribute($value)
{
/*$query = $this->where('parent', '1')
->max('order');*/
//$this->attributes['nombre'] = Hash::make($value);
$this->attributes['order'] = 1;
}
public function sluggable()
{
return [
'slug' => [
'source' => 'nombre'
]
];
}
}