Home > Mobile >  Laravel migration to edit existing table data
Laravel migration to edit existing table data

Time:12-31

I'm very much new to Laravel and backend, so I got quite lost here. I need to loop through all the rows in a table and edit the data of a field based on a condition.

The field consists of a url and I want to add http at the start. I already have that function but I cant write the migration to loop through all the fields. Can anyone help?

I think I'm mainly having trouble accessing the table here.

public function up()
{
  Schema::table('firms', function (Blueprint $table) {
    $results = $table::where()->select('url')->get();
    foreach ($results as $urls) {
      $start = parse_url($urls->url, PHP_URL_SCHEME);
      if ($start !== 'http' && $start !== 'https') {
        $url = 'http://'.$urls->url;
        DB::table('firms')->where('url', $url)->update(['url' => $url]);
      }
      if ($start === 'http' || $start === 'https') {
        continue;
      }
    }
  });
}

CodePudding user response:

You can do something like this:

If you have Firm model:

// looping only to firms which url field is not starting with http
foreach(Firm::where('field', 'value')->where('url', 'not like', 'http%')->get() as $firm){
    //updating single firm adding http://
    $firm->update(['url' => 'http://' . $firm->url]);
}

//or in just one line:
Firm::where('url', 'not like', 'http%')->update(['url' => DB::raw("CONCAT('http://', url)")]);

in this case where('field', 'value') is an optional other condition, you can remove it.

The first solution updates updated_at field, the second doesn't

If you DON'T have Firm model:

DB:raw("Update firms set url = CONCAT('http://', url) where url not like 'http%'");

as @brombeer pointed out, do it in an artisan command is much cleaner

  • Related