Search code examples
phplaravellaravel-4preg-replacetrim

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);  

    }

Solution

  • 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.