Hobby99
Hobby99

Reputation: 703

Unable to trim each database record

I want to retrieve database records, trim them and then re-insert them. I tried it with both the trim- and the pre_replace function but for both cases only some of the records are trimmed and not all.

Is the code correct? I don't know what is wrong, maybe something simple. Thank you for any help!

    $table = DB::table('countries');
    $result = $table->get();
    $array = array();
    foreach($result as $item){
        $array[$item->id] = array(
            'name_en' => preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $item->name_en),
            'name_de' => preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $item->name_de)
        );
    }

    foreach($array as $item_id => $newItem){
        $update = $table->where('id', $item_id)->update($newItem);  

    }

Upvotes: 0

Views: 57

Answers (2)

ArjanSchouten
ArjanSchouten

Reputation: 1368

You can alternatively update with laravel by adding a parameter to the object and call the save method:

$table = DB::table('countries');
$result = $table->get();
$array = array();
foreach($result as $item){
    $item->name_en =  preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $item->name_en);
    $item->name_de = preg_replace('/^\p{Z}+|\p{Z}+$/u', '', $item->name_de);
    $item->save();
}

I think the problem was that you don't update the value correctly. I suppose trim should then work for you.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

It seems you should use:

$update = DB::table('countries')->where('id', $item_id)->update($newItem);  

instead of:

$update = $table->where('id', $item_id)->update($newItem);  

It worked for me but of course for big data set it will take a lot of time.

Upvotes: 1

Related Questions