Skip to content

Instantly share code, notes, and snippets.

@graciano
Created March 15, 2016 20:00
Show Gist options
  • Save graciano/41ff91fef6fbc4f48b08 to your computer and use it in GitHub Desktop.
Save graciano/41ff91fef6fbc4f48b08 to your computer and use it in GitHub Desktop.
Create random users in laravel for test in facebook graph api using faker
{
//...
"require": {
"php": ">=5.5.9",
"laravel/framework": "5.2.*",
"facebook/php-sdk-v4": "^5.1"
},
"require-dev": {
"fzaninotto/faker": "~1.4",
}
//....
}
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('avatar')->nullable(); //optional
$table->string('facebook_id')->unique();
// $table->string('password'); //in my case, I only use facebook for authentication
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('users');
}
}
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(FacebookUsersSeeder::class);
}
}
class FacebookUsersSeeder extends Seeder
{
public function run(){
$faker = \Faker\Factory::create();
foreach(range(0,20) as $i) {
$user = new App\User([
'name' => "$faker->firstName $faker->lastName",
'created_at' => $faker->dateTimeBetween('-6 years', 'now')
]);
$facebook = new \Facebook\Facebook([
'app_id' => env('FACEBOOK_APP_ID'),
'app_secret' => env('FACEBOOK_APP_SECRET'),
]);
$response = $facebook->post('/'.env('FACEBOOK_APP_ID').'/accounts/test-users',
[
'name' => $user->name,
'password' => '123456',
'installed' => 'true',
'access_token' => env('FACEBOOK_ACCESS_TOKEN'),
]
);
if($response->getHttpStatusCode()===200){
$fbUser = $response->getGraphUser();
$user->facebook_id = $fbUser->getId();
$user->email = $fbUser->getEmail();
$user->save();
$this->command->comment("User $i -> $user->name created succesfully");
}
else{
$this->command->error("Error in request");
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment