Search code examples
phplaraveltinker

How to seed a database dummy data using tinker with two each loops - Laravel PHP


I try to seed my mysql database with tinker commands and are struggeling combining two each loops...

I have a table movies, users, and ratings. I want to seed the database with 10 movies, 3 users, and for each user a rating for each movie.

I am putting data into the two tables users und movies and saving those to $movies and $users. And try to create 3 ratings with the user_id and the movie_id for each movie with the following lines.

$users = factory('App\User',3)->create();
$movies= factory('App\Movie',10)->create();
$movies->each(function($movie){ $users->each(function($user){ factory('App\Rating',3)->create(['movie_id'=>$movie->id,'user_id'=>$user->id]);}); });

echoing out $movies and $users show me the data are in there. The last line gives me back an error: HP Notice: Undefined variable: users on line 2

tried to simplify the syntax for testing:

$movies->each(function ($movie) {$users->each(function($user) {echo $movie;});});

with the same error.

I guess it is that the $users variable isn't defined inside the first function? Do I have to define $users inside the first function? How do i do that if i dont want to create 3 new users for each movie? Maybe i can use a for loop somehow to iterate through the users and retrieve the users ids that way?

thanks in advance for helping me


Solution

  • Be sure to use ($users) as well. You need declare the variables used out of the function scope when using Closures in PHP!

    $movies->each(function($movie) use ($users){ 
        $users->each(function($user) use ($movie){ 
            factory('App\Rating',3)
         ->create(['movie_id'=>$movie->id,'user_id'=>$user->id]);
        }); 
    });