Urarii
Urarii

Reputation: 67

laravel 5 update in database

I created a row in my 'movies' table called 'slug' where i want to store the slug of the titles of my movies.the problem is i already have 250 movies and i don't want to manually enter the slug to each one of them so i am trying to make a script to automatically update all the slugs.But i failed to do that:

This is my code in FilmController.php:

class FilmController extends Controller {

public function film()

  {
    $title = DB::table('movies')->select('title');
    $slug = str_replace(" ","-",$title);
    DB::table('movies')->update(array('slug' => $slug));
  }
}

And this is in my routes:

Route::get('update','FilmController@film');

This is the error that pops up when i go to localhost/update:

Object of class Illuminate\Database\Query\Builder could not be converted to string

Can somebody tell me how could i change my code so i can put in my slug field in all the movies the title of the movie with '-' insted of space between the words?

Upvotes: 0

Views: 123

Answers (2)

Daniel Katzan
Daniel Katzan

Reputation: 564

$title is an object containing all titles, and not a string,so str_replace will not work on it you can try using a loop to update each record according to its title

something like

$titles = DB::table('movies')->select('title','id')->get();
foreach ($titles as $title){
     $slug = str_replace(" ","-",$title->title);
     DB::table('movies')->where('id',$title->id)->update(array('slug' => $slug));
}

Upvotes: 1

Carlos Herrera Plata
Carlos Herrera Plata

Reputation: 993

I recomend use a seeder if you want to make a script that update or create default info on your database. Laravel Database Seeding doc

And title have a collection of titles not a single title.

Upvotes: 0

Related Questions