Skip to content

Sample Data Using Laravel

Rati Wannapanop edited this page Apr 15, 2016 · 4 revisions

Sample Data Using Laravel

  • create a new laravel project. See here

  • update the migration for users table in database/migrations/ path to look like this:

     public function up()
     {
         Schema::create('users', function (Blueprint $table) {
             $table->increments('id');
             $table->string('name');
             $table->string('nickname');
             $table->string('email')->unique();
             $table->string('password');
             $table->date('birthdate');
             $table->char('gender');
             $table->integer('group_id')->unsigned();
             $table->rememberToken();
             $table->timestamps();
         });
     }
  • then, modify App\User factory in database/factories/ModelFactory.php to look like this

     $factory->define(App\User::class, function (Faker\Generator $faker) {
         return [
             'name' => $faker->name,
             'nickname' => $faker->word,
             'email' => $faker->safeEmail,
             'password' => bcrypt(str_random(10)),
             'remember_token' => str_random(10),
             'birthdate' => $faker->dateTimeBetween('-30 years', 'now'),
             'gender' => $faker->randomElement(['M', 'F']),
             'group_id' => $faker->randomElement([1, 2, 3, 4, 5])
         ];
     });
  • from the command prompt, run the migration using this command

     php artisan migrate
  • and still in the command prompt, run artisan tinker command

     php artisan tinker
  • when you see the prompt >>>, enter this command to generate fake data

     factory(App\User::class, 50)->create()
  • now open app\Http\routes.php file and replace it with the following code

     <?php
    
     Route::get('/api/users', function() {
     	// handle sort option
         if (request()->has('sort')) {
             list($sortCol, $sortDir) = explode('|', request()->sort);
             $query = App\User::orderBy($sortCol, $sortDir);
         } else {
             $query = App\User::orderBy('id', 'asc');
         }
    
         $perPage = request()->has('per_page') ? (int) request()->per_page : null;
    
     	// The headers 'Access-Control-Allow-Origin' and 'Access-Control-Allow-Methods'
     	// are to allow you to call this from any domain (see CORS for more info).
     	// This is for local testing only. You should not do this in production server,
     	// unless you know what it means.
         return response()->json(
         		$query->paginate($perPage)
     		)
         	->header('Access-Control-Allow-Origin', '*')
         	->header('Access-Control-Allow-Methods', 'GET');
     });

Clone this wiki locally