Home > Blockchain >  php laravel eloquent object can not be changed
php laravel eloquent object can not be changed

Time:12-30

I have a weird bug, I dont know why it will not work. So I am using Laravel php framework and getting from db a object. Since some decimal number looks like this : '.00', I want to change it to this '0', but it cannot be changed when I loop through it. It looks like this:

 $stipendien = Stipendium::where('id','=',$request->input('id'))->get()->toArray();


        
        foreach($stipendien as $object => $test)
        {
            foreach($test as $key => $value)
            {
                if($test[$key] == ".00")
                {
                    $test[$key] = "0";
                }
            }
        }
return $stipendien;

Should not the '$stipendien' be changed when I assign the value new, since it does go to the if statement and getting the correct key ?

array:2 [
  0 => array:17 [
    "id" => 1
    "Kosten_Kurs" => "22.00"
    "Kosten_Prüfung" => ".00"
    "Kosten_Unterlagen" => ".00"
    "Kosten_Lernurlaub" => ".00"
    "Kosten_Reise" => ".00"
    "Kosten_Sonstig" => ".00"

  ]
  1 => array:17 [
    "id" => 2
    "Kosten_Kurs" => "22.00"
    "Kosten_Prüfung" => "2.00"
    "Kosten_Unterlagen" => ".00"
    "Kosten_Lernurlaub" => ".00"
    "Kosten_Reise" => ".00"
    "Kosten_Sonstig" => ".00"
  ]
]

But when I return it, it did not change at all. What did I wrong here?

CodePudding user response:

check that your condition is matched by adding dd() or die inside this if

if($test[$key] == ".00")
{
   $test[$key] = "0";
}

CodePudding user response:

You may try using this in loop while assigning 0

 $stipendien[$object][$key] = "0";

CodePudding user response:

You can simply use laravel accessor for this purpose instead of using nested loops In your controller use something like this

  use App\Models\User;
 $user = User::find(1);
 $firstName = $user->first_name; 

And then in your Model.

public function getFirstNameAttribute($value)
{
    return ucfirst($value);
}

Here is the official documentation of the laravel.

  • Related