Reputation: 677
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
Upvotes: 4
Views: 5770
Reputation: 15579
Assuming you have a Team
model:
$teams = App\Team::all();
foreach($teams as $team) {
$team->slug = str_slug($team->name, "-");
$team->save();
}
You're trying to use Eloquent ORM syntax ($team->save
) in a code that is actually using Query Builder. You'd better choose one or the other (ORM or Query building). My version uses Eloquent ORM. Of course you could have used Query Builder syntax all the way, like this:
$teams = DB::table('teams');
foreach($teams as $team) {
DB::table('teams')
->where('id', $team->id)
->update(['slug' => str_slug($team->name)]);
}
And basically a Query Builder select command (like $teams = DB::table('teams');
) will return an array of stdClass objects (which have not a "save" method) , whereas Eloquent ORM select will return a collection of objects of the specified model, which do have the "save" method.
Upvotes: 9
Reputation: 15579
You are not using the name
column, but the (empty) slug
. Try this instead:
$team->slug = str_slug($team->name, "-");
Upvotes: 1