I am developing a site where it has a modal banners and want to set a field in the database of the "order", where I can decide which banner appears first, second, third ... in my admin panel I I have a list of all banners and banner that is third I need to set it to first, fourth to second, first to third, that is, you can change their order after registered. I used the code below, it works only 3 times and then it starts to bug, it does not work. I really need help to do this, set order for them and save the order in the database.
private function ordenaPosicionamento($posicaoAntiga, $novaPosicao)
{
if($novaPosicao == 1)
{
// busca todos banners num array
$banners = Banner::where('status', '=', true)->get();
// busca o banner para ser alterado e seta um valor temporario para alteracao
$bannerParaAlteracao = $banners[$posicaoAntiga - 1];
$bannerParaAlteracao->ordem = 0;
// sobe a posicao dos anteriores
for($i2 = $posicaoAntiga; $i2 < count($banners); $i2++)
{
$banners[$i2]->ordem = $banners[$i2]->ordem - 1;
}
// ajusta a posicao de todos {final}
for($i4 = 0; $i4 < count($banners); $i4++)
{
$banners[$i4]->ordem = $banners[$i4]->ordem + 1;
//echo "NOME " . $banners[$i4]->nome . " ORDEM " . $banners[$i4]->ordem . "<br>";
//$banners[$i4]->save();
}
foreach($banners as $banner)
{
$banner->save();
}
}
}
My database has the following fields: id, status, order, name