Search code examples
laravelfaker

syntax error, unexpected '$factory' (T_VARIABLE), expecting function (T_FUNCTI ON) or const (T_CONST)


currently i m using laravel 8.17.*

i m trying to to add data using faker library but given error "syntax error, unexpected '$factory' (T_VARIABLE), expecting function (T_FUNCTION) or const (T_CONST)" Help me to solve this error

ProductFactory.php

<?php

  namespace Database\Factories;

  use App\Models\Model\Product;
  use Illuminate\Database\Eloquent\Factories\Factory;
  use Illuminate\Support\Str;
  use Faker\Generator as Faker;
  
   class ProductFactory extends Factory
   {
     /**
       * The name of the factory's corresponding model.
       *
       * @var string
       */
       protected $model =  \App\Models\Model\Product::class;

       /**
         * Define the model's default state.
         *
         * @return array

      public function definition()
      {
       return [
        //
       ];
      } */


     $factory->define(App\Models\Model\Product::class,function(Faker $faker){
    return [
        'name'=>$this->$faker->Word,
        'detail'=>$this->$faker->paragraph,
        'price'=>$this->$faker->numberBetween(99,999),
        'stock'=>$this->$faker->randomDigit,
        'discount'=>$this->$faker->numberBetween(2,30)
    ];
 });
}

**[enter image description here][1] [1]: https://i.sstatic.net/CvZND.png


Solution

  • Laravel 8 introduces class based model factories so the sample definition must be like

    <?php
    
      namespace Database\Factories;
    
      use App\Models\Model\Product;
      use Illuminate\Database\Eloquent\Factories\Factory;
      use Illuminate\Support\Str;
      use Faker\Generator as Faker;
      
       class ProductFactory extends Factory
       {
            /**
             * The name of the factory's corresponding model.
             *
             * @var string
             */
             protected $model =  \App\Models\Model\Product::class;
    
            /**
             * Define the model's default state.
             *
             * @return array
             */
    
            public function definition()
            {
                return [
                    'name'=>$this->faker->Word,
                    'detail'=>$this->faker->paragraph,
                    'price'=>$this->faker->numberBetween(99,999),
                    'stock'=>$this->faker->randomDigit,
                    'discount'=>$this->faker->numberBetween(2,30)
                ];
            }
        }