Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migration - Create a new column filled from existing column

I'm trying to create a migration that makes a new column and fills it with data from existing column.

I want to turn the name column into a slug (using the helper function) and save that in a slug column.

I've tried this but no luck:

public function up()
{
    Schema::table('teams', function(Blueprint $table)
    {
        //
        $table->string('slug', 100);
    });

    $teams = DB::table('teams')->get();

    foreach ($teams as $team)
    {
        $team->slug = str_slug($team->name, "-");
        $team->save();
    }
}

Am i being an idiot? Can i make this work?

Thanks

like image 696
Ryk Waters Avatar asked Feb 09 '23 22:02

Ryk Waters


1 Answers

You are not using the name column, but the (empty) slug. Try this instead:

$team->slug = str_slug($team->name, "-");
like image 147
Amarnasan Avatar answered Feb 11 '23 18:02

Amarnasan