Home > Software engineering >  Laravel & PHP8 Newbie: Tinker says a class isn't defined, but it's the wrong class?
Laravel & PHP8 Newbie: Tinker says a class isn't defined, but it's the wrong class?

Time:12-05

Below is my CategoryFactory.php file contents.

When I run php artisan tinker and App\Models\Category::factory()->create() it throws an error saying

PHP Error: Class "Database\Factories\Str" not found in /Users/[my_name]/.composer/vendor/bin/blog/database/factories/CategoryFactory.php on line 17

Line 17 is the one where I declare $name

Why is it looking for Database\Factories\Str when I've declared Illuminate\Support\Str?

Please and thank you.

<?php

namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class CategoryFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        $name = $this->faker->words(2);
        $slug = Str::slug($name,'-');

        return [
            'name' => $name,
            'slug' => $slug
        ];
    }
}

CodePudding user response:

Moving the site to a proper directory seems to have done the trick, though I'm not certain that was the only thing I did that contributed to the fix. I still have a weird issue which I'm moving to a new question.

CodePudding user response:

I didnt see any error in namespace or imported functions, but why you didnt add Category model in your factory?

<?php
namespace Database\Factories;

use App\Models\Category;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

class CategoryFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array
     */

    protected $model = Category::class;

    public function definition()
    {
        $name = $this->faker->words(2);
        $slug = Str::slug($name,'-');

        return [
            'name' => $name,
            'slug' => $slug
        ];
    }
}

  • Related