Database seeding in Laravel 4 using randomuser.me



Introduction

Database seeding in Laravel 4 can be quite cumbersome for things such as user information. Luckily there are tools that can help us with that!

Recently I have been using http://randomuser.me/ for filling up my database with randomly generated user profiles.

Configure Laravel

First you should have a way to retrieve data from an external API. For this I have chosen anlutro/curl as it comes recommended and it is very easy to use.

Add “anlutro/curl”: “dev-master” to your composer.json file

"require": {
...
"anlutro/curl": "dev-master"
}

Run “php composer.phar update” to download the package, next update your app.php file to include the service provider and alias.

Provider:

'providers' => array(
...
    'Illuminate\Workbench\WorkbenchServiceProvider',
    'anlutro\cURL\Laravel\cURLServiceProvider',
)

Alias:

'aliases' => array(
....
    'cURL' => 'anlutro\cURL\Laravel\cURL'
)

 Using randomuser.me

Now that everything is set up, you can grab the data from the randomuser API using the cURL library by adding the following line, for example, in your seed file:



$curl = new cURL;
$response = $curl->get('http://api.randomuser.me/?results=5');
$users = json_decode($response, true);

This will give you a json response that cointains 5 user profiles that are randomly generated and ready to seed!

Next thing would be to insert the users, simple as pie!

foreach ($users['results'] as $user) {
    $userInfo = array(
        'username' => $user['user']['name']['first'] . $user['user']['name']['last'],
        'password' => Hash::make($user['user']['password']),
        'email' => $user['user']['email'],
        'firstname' => $user['user']['name']['first'],
        'lastname' => $user['user']['name']['last'],
        'picture' => $user['user']['picture'],
        'gender' => $user['user']['gender'],
        ...
    );

    DB::table('profiles')->insert($userInfo);

}

That’s it! you now have 5 randomly generated user profiles in your database!

You can even only add male profiles by specifying the GET parameter “gender” in the URL.

http://api.randomuser.me/?gender=male

Or if you prefer to always get the same results you can specify a seed as such:

http://api.randomuser.me/?seed=testing123

More info on the abilities of the RandomUser API can be found on the official website

Share the knowledge!
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on StumbleUpon372Share on Reddit1Share on LinkedIn10Share on TumblrBuffer this pageDigg this

Comments

You may also like...

Stay updated
Subscribe!