Reputation:
I'm new to Laravel and I've been trying to generate fake data into my DB using Laravel but I'm getting the error Undefined variable:factory. Can the following command still be used in laravel8? If not, which other code can be used to display data?
CategoryFactory
$factory->define(Category::class,function (Faker $faker){
$title = $faker->sentence;
return[
'title'=>$this->faker->sentence,
'slug'=>Str::slug($title),
];
});
Category Seeders
namespace Database\Seeders;
use App\Models\Category;
use Illuminate\Database\Seeder;
class CategorySeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Category::factory()->count(10)->create();
}
}
Category Migration
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->id();
$table->string("title");
$table->string("slug",191)->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
Upvotes: 0
Views: 588
Reputation: 2243
In Laravel 8.X, model factories have been rewritten for the usage of classes.
If you want to use the legacy Factory in Laravel 8.X, you have to install the package: composer require laravel/legacy-factories
.
If you did not write any Factory yet, however, I would advice of using the definition()
function in the CategoryFactory
class as shown in your example. The other code can be removed.
For more information about Factories and how to write and use them, please consult the Laravel documentation.
Upvotes: 1
Reputation: 379
add on this two line on return
public function definition()
{
return [
'title'=>$this->faker->sentence,
'slug'=>Str::slug($title),
];
}
=> remove this two line on top
$factory->define(Category::class,function (Faker $faker){
$title = $faker->sentence;
Upvotes: 0