获取Parse错误:语法错误,播种时出现意外的'$ faker'错误

时间:2017-07-02 11:31:50

标签: laravel-5.4 seeding laravel-seeding

尝试在Laravel 5.4中播种时出现以下错误

 [Symfony\Component\Debug\Exception\FatalThrowableError]                                            
Parse error: syntax error, unexpected '$faker' (T_VARIABLE), expecting function (T_FUNCTION) or c  
onst (T_CONST)

以下是种子文件的代码。

<?php

use Illuminate\Database\Seeder;
use App\Book;
use Faker\Factory as Faker;

class BookSeeder extends Seeder
{
/**
 * Run the database seeds.
 *
 * @return void
 */
 $faker = Faker::create();

public function run()
{
  foreach (range(1, 30) as $index) {
    Book::create([
      'title'=> $faker->sentence(5),
      'author'=> $faker->sentence(7),
      'description'=>$faker->paragraph(4)
    ]);
  }
}

}

我创建了模型并完成了迁移。我似乎无法找到有关如何使用Laravel 5.4进行此操作的任何好教程。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

在run方法中声明$ faker变量将解决问题

`<?php
   use Illuminate\Database\Seeder; 
   use App\Book; use Faker\Factory as Faker; 

   class BookSeeder extends Seeder 
   { 
       /** 
       * Run the database seeds. * 
       * @return void */ 
       public function run() { 

       $faker = Faker::create(); 

       foreach (range(1, 30) as $index) { 
            Book::create([ 
                    'title'=> $faker->sentence(5), 
                    'author'=> $faker->sentence(7), 
                    'description'=>$faker->paragraph(4) 
                   ]); 
       } 
   }
  }`