Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Laravel migration to edit existing table data

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading