Reputation: 13
Hi I am new to creating factories on Laravel and I am setting up a blog website. There is no need for users at this time as it is a draft but I am trying to set up a factory to create dummy blog posts.
I have a Post.php file which looks like this:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
public $primaryKey = 'id';
public $timestamps = true;
}
My PostFactory looks like this
use App\Post;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(App\Post::class, function (Faker $faker) {
return [
'title' => $faker->name,
'body' => $faker->unique()->safeEmail,
];
});
but everytime i try to create the records it throws this error "InvalidArgumentException with message 'Unable to locate factory for [App/Post].'" i know its about linking these files but i cannot figure out how to do it.
Upvotes: 1
Views: 997
Reputation: 2709
First as mentioned above your file must be named Post.php and not posts.php.
Since you are using App\Post at the beginning of your file, you can simply call Post::class
$factory->define(Post::class, function (Faker $faker)
Another option could also be that you are missing the factories folder in your composer classmap:
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/seeds",
"database/factories"
]
},
If this does not solve the problem, then you might need to post your code where you are calling your factory
@edit
this is pretty good overview over conventions
Upvotes: 3