Laravel 8 factory not found despite dumping composer autoloader - php

I'm creating factories in my Laravel 8 project, I've used them before so am quite familiar with their set up.
In my project, I'm having trouble getting Laravel to pick up my factories and cannot figure out why, the error I'm getting is that my factory class can't be found, I've tried composer dump-autoload and also have tried various cache clearing commands with no result.
What am I missing?
My database/factories/BrandFactory is:
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Carbon\Carbon;
class BrandFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = Brand::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
$todo = $this->faker->unique()->company();
$slug = Str::slug($brand);
return [
'user_id' => User::all()->random()->id,
'brand' => $brand,
'slug' => $slug,
'url' => $this->faker->domain(),
'created_at' => Carbon::now()->subDays(rand(1, 14))
];
}
}
I have HasFactory on my model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Brand extends Model
{
use HasFactory, SoftDeletes;
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'brands';
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'brand',
'url'
];
/**
* The relationships that should always be loaded.
*
* #var array
*/
protected $with = [
'form'
];
/**
* Get the form associated with the user.
*/
public function form()
{
return $this->hasOne(Form::class);
}
/**
* Get the brand that owns the comment.
*/
public function brand()
{
return $this->belongsTo(User::class);
}
}
Which is called from my seeder:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\Brand;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
Brand::factory(3)->create();
}
}
Also, since this is a Laravel 8 project, autoloader is configured correctly to:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
}

Your code look fine, anyway, you can tell your model to find it's own factory using newFactory method:
In your model:
protected static function newFactory()
{
return Database\Factories\BrandFactory::new();
}

Related

Problem with Class 'Database\Seeders\ not found

recently i start to practice laravel/lumen. Everything was fine but now i am facing a problem when i am going to try the command: php artisan db:seed It is showing me a error that: Class 'Database\Seeders\lumenPractice' not found
i also tried: php artisan migrate:fresh --seed it is also not working and showing me the same error. i am using php version 7.4.11enter code here
my LumenPractice.php code are given below:
<?php
namespace App\Models;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class LumenPractice extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'gender',
'country',
];
}
My DatabaseSeeder.php code are given below:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//factory(lumenPractice::class(), 50)->create();
lumenPractice::factory(count(30))->create();
// $this->call('UsersTableSeeder');
}
}
My UserFactory.php code are given below:
<?php
namespace Database\Factories;
use App\Models\LumenPractice;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = LumenPractice::class;
/**
* Define the model's default state.
*
* #return array
*/
public function definition()
{
return [
'gender' =>$gender = $this->faker->randomElement(['male''female'])
'name' => $this->faker->name($gender),
'country' => $this->faker->country,
];
}
}
Have you tried capitalizing the "l" in lumenPractice::factory(count(30))->create();? I believe you meant to write LumenPractice::factory(count(30))->create(); . Everything else seems fine.

Subscription won't update in database after subscription is updated in Stripe using Laravel Cashier and Jenssegers MongoDB

I am having trouble getting my new subscription to be updated in MongoDB Database. Im using Laravel Cashier, Stripe, and Jenssegers MongoDB.
In the stripe dashboard, users have been successfully added as customers and subscribers.
Here is the ERROR:
[23:24:17] LOG.error: Call to a member function prepare() on null
{"userId":"4ec1b45d36623t2269477d0...
Here is where the ERROR lives:
return true;
}
$statement = $this->getPdo()->prepare($query);
$this->bindValues($statement, $this->prepareBindings($bindings));
Here is my controller:
namespace App\Http\Controllers;
use App\Plan;
use App\User;
use Exception;
use Illuminate\Http\Request;
class CheckoutController extends Controller
{
/**
* The collection name
*
* #var array
*/
public function checkout($plan_id)
{
$plan = Plan::findOrFail($plan_id);
$intent = auth()->user()->createSetupIntent();
return view('billing.checkout', compact('plan', 'intent'));
}
public function process(Request $request)
{
$plan = Plan::findOrFail($request->input('billing_plan_id'));
try {
auth()->user()->newSubscription($plan->name, $plan->stripe_plan_id)-
>create($request->input('payment-method'));
return redirect()->route('billing')->withMessage('Subscribed Successfully');
} catch (Exception $e) {
return redirect()->back()->withError($e->getMessage());
}
}
Here is My User Model:
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\Model;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Laravel\Cashier\Billable;
use Illuminate\Foundation\Auth;
class User extends Authenticatable
{
use Billable, Notifiable;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password', 'phone', 'last_login_at',
'last_login_ip',
];
/**
* The collection name
*
* #var array
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Here is My Plan Model:
namespace App;
use Jenssegers\Mongodb\Eloquent\Model;
/**
* #method static findOrFail($plan_id)
*/
class Plan extends Model
{
protected $fillable = [
'name',
'price',
'stripe_plan_id'
];
}
Here is my Subscription Migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Migrations\Migration;
use Jenssegers\Mongodb\Schema\Blueprint;
class CreateSubscriptionsTable extends Migration
{
/**
* The name of the database connection to use.
*
* #var string
*/
protected $connection = 'mongodb';
public function up()
{
Schema::create('subscriptions', function (Blueprint $collection) {
$collection->bigIncrements('id');
$collection->unsignedBigInteger('userid');
$collection->string('name');
$collection->string('stripe_id');
$collection->string('stripe_status');
$collection->string('stripe_plan')->nullable()->change();
$collection->integer('quantity')->nullable()->change();
$collection->timestamp('trial_ends_at')->nullable();
$collection->timestamp('ends_at')->nullable();
$collection->timestamps();
$collection->index(['user_id', 'stripe_status']);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('subscriptions');
}
}
Please help me figure out the source of this issue and how to solve it.
Make sure your model (i'm guessing it's a model but you didn't mention / show it) that is calling $this->getPdo() is extending Jenssegers eloquent model class and not Laravels.
For example:
Replace
class MyModel extends Model
With
class MyModel extends \Jenssegers\Mongodb\Eloquent\Model
Partial Solution:
Although I am getting the same error below
"Call to a member function prepare() on null {"userId":"4ec1b45d36623t2269477d0...".
In order to get the Subscription to update in the database I went into the Subscription.php file in Cashier and I replaced
use Illuminate\Database\Eloquent\Model;
with
use Jenssegers\Mongodb\Eloquent\Model;
This will fix database update issue, but something wierd is still going on in the Connection.php file causing the error.
$statement = $this->getPdo()->prepare($query);

Laravel 5.6 - Seeder Class not found

I'm trying to populate a Laravel 5.6 project DB - following the offial docs - without success. php artisan db:seed throws this exception:
Symfony\Component\Debug\Exception\FatalThrowableError : Class 'App\Item' not found
at /Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:217
Exception trace:
1 Illuminate\Database\Eloquent\FactoryBuilder::make([])
/Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:167
2 Illuminate\Database\Eloquent\FactoryBuilder::create()
/Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/database/seeds/ItemTableSeeder.php:14
I already tried most of the common suggestions provided from the community, like this one, as well as:
Trying with composer self-update + composer dump-autoload;
On my composer.json the autoload property is set as is:
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
(Tried to put classmap in autoload-dev too).
Here's the situation:
ItemFactory.php
<?php
use Faker\Generator as Faker;
// Definizione dati test
$factory->define(App\Item::class, function (Faker $faker) {
return [ ...]
}
ItemTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ItemTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\Item::class, 25)->create();
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(ItemTableSeeder::class);
}
}
At last, I tried to put dependencies directly in sources too:
use App\Item;
use Illuminate\Database\Seeder;
by removing the App\ prefix and leave only Item::class in the argument:
factory(Item::class, 25)->create();
All these tries didn't helped, so I'm actually stuck.
If anyone could show me the way, it should be really appreciated.
Thanks in advance to all.
UPDATE
#kerbholz & #h-h: There was a mistyped trait in ItemTableSeeder.php, thanks for both your suggestion. Yes, in first place I implemented an Item.php model like this:
<?php
// Definizione Namespace
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* Classe Item
*/
class Item extends Model
{
use SoftDeletes;
// Dichiarazione Proprietà
protected $table = 'item';
protected $dateformat = 'Y-m-d';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'data_acquisto',
'labeled',
'estensione_garanzia',
'stato',
'data_dismissione',
'note'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'codice',
'serial',
'componente_id',
'tipologia_id',
'condizione_id',
'locazione_id',
'fornitore_id',
'parent_id'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'data_acquisto',
'data_dismissione',
'deleted_at'
];
/**
* All of the relationships to be touched.
*
* #var array
*/
protected $touches = [
'componenti',
'condizioni',
'fornitori',
'locazioni',
'tipologie'
];
/**
* Scope query item figli
* Getter
* #param array $query Query
* #return array Query
*/
public function scopeFigli($query)
{
return $query->where('parent_id', '!=', null);
}
/**
* Componenti Correlati
* Getter
* #return object Componenti
*/
public function componenti()
{
// Definizione relazione
return $this->belongsTo('App\Componente');
}
/**
* Condizioni Correlate
* Getter
* #return object Condizioni
*/
public function condizioni()
{
// Definizione relazione
return $this->belongsTo('App\Condizione');
}
/**
* Fornitori Correlati
* Getter
* #return object Fornitori
*/
public function fornitori()
{
// Definizione relazione
return $this->belongsTo('App\Fornitore');
}
/**
* Locazioni Correlate
* Getter
* #return object Locazioni
*/
public function locazioni()
{
// Definizione relazione
return $this->belongsTo('App\Locazione');
}
/**
* Tipologie Correlate
* Getter
* #return object Tipologie
*/
public function tipologie()
{
// Definizione relazione
return $this->belongsTo('App\Tipologia');
}
}
Meanwhile I continued to implement others. Now, after correcting the mistype and run again twice a composer dump-autoload seeding started. It populated some tables, but after that thrown a new exception. Here's an extract from last try:
Seeding: ItemTableSeeder
ErrorException : Illegal offset type
at /Applications/MAMP/htdocs/greylab/inventario/greylab_inventario/vendor/laravel/framework/src/Illuminate/Database/Eloquent/FactoryBuilder.php:257
253| * #throws \InvalidArgumentException
254| */
255| protected function getRawAttributes(array $attributes = [])
256| {
257| if (! isset($this->definitions[$this->class][$this->name])) {
#h-h: In this case, I tried to put backslash before "App": \App\Item::class with no success. Dunno if it's related to some faker misconfiguration...
Found it.
Inside ItemFactory.php I put a stupid $this as factory parameter, in a relation creation:
$factory->define(App\Item::class, function (Faker $faker) {
[...]
'parent_id' => function() {
return factory($this)->create()->id;
}
}
By changing the return sentence in this way:
return factory(App\Item::class)->create()->id;
the issue seems to be solved.
Thanks everyone for the assistance.
You need to either import the Item class like so:
use App\Item;
which means you can do this:
factory(Item::class, 25)->create();
--
Or put a \ before hand like so:
factory(\App\Item::class, 25)->create();
--
Also make sure your Item class has this at the top:
namespace App;
Normally Seeder Class Not Found error occurs, when we have different git branches and we checkout to new branch.
php artisan db:seed --class=StockBranchFileSeeder
Exception: For Target class [StockBranchFileSeeder] does not exist.
Seeder Exception
So I resolved this issue simply run below code in project root;
composer dump-autoload
now Seeder has been successfully executed.

Laravel Caffeinated Modules Model Factory - Unable to locate factory with name

I appreciate this question does appear on here many times, however after looking through the answers and attempting to resolve the issue, it unfortunately still persists.
I am using the Caffeinated Modules for Laravel package with Laravel 5.6. I have created a User module which contains the following.
UserTableSeeder App/Modules/User/Database/Seeds/UserTableSeeder.php
<?php
namespace App\Modules\User\Database\Seeds;
use Illuminate\Database\Seeder;
use App\Modules\User\Models\User;
class UserTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(User::class, 3)->create();
}
}
UserFactory App/Modules/User/Database/Factories/UserFactory.php
<?php
use Faker\Generator as Faker;
use App\Modules\User\Models\User;
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/
$factory->define(User::class, function (Faker $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
'remember_token' => str_random(10),
];
});
UserDatabaseSeeder App/Modules/User/Database/Seeds/UserDatabaseSeeder.php
<?php
namespace App\Modules\User\Database\Seeds;
use Illuminate\Database\Seeder;
class UserDatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UserTableSeeder::class);
}
}
User App/Modules/User/Models/User.php
<?php
namespace App\Modules\User\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
When I run
php artisan module:seed
the UserDatabaseSeeder calls the UserTableSeeder but produces the following error message:
Seeding: App\Modules\User\Database\Seeds\UserTableSeeder
InvalidArgumentException : Unable to locate factory with name
[default] [App\Modules\User\Models\User].
Any help is much appreciated.
Basically Caffinated Modules doesn't support loading factories from your module out of the box.
I found this issue that includes a fix: https://github.com/caffeinated/modules/issues/337
Add this to your ModuleServiceProvider:
/**
* Register the module services.
*
* #return void
*/
public function register()
{
$this->app->register(RouteServiceProvider::class);
$this->mergeConfigFrom(
__DIR__.'/../config.php',
'user'
);
$this->registerEloquentFactoriesFrom(__DIR__.'/../Database/Factories');
}
/**
* Register factories.
*
* #param string $path
* #return void
*/
protected function registerEloquentFactoriesFrom($path)
{
$this->app->make(Factory::class)->load($path);
}

Laravel 5.0 phpunit models

I have clean install of Laravel 5.0, and I have issues with phpunit tests.
If I create a test for user model, I'm getting error - User class not found.
If I test controllers, works fine, controller classes are detected.
As a temporary workaround, just to test if it is working, I added class User inside UserTest.php.
I tried to add folder models in app folder, placing the class inside, similar as it was in Laravel 4.2, changed composer.json as well, ran composer dump-autoload, but it didn't work.
"autoload": {
"classmap": [
"database",
"app/model"
],
"psr-4": {
"App\\": "app/",
}
},
The simple classes looks like this:
// tests/models/UserTest.php
class UserTest extends TestCase
{
protected $user;
public function setUp()
{
parent::setUp();
}
public function testEmptyNameFailExpected()
{
$user = new User;
$user->name = '';
$result = $user->isValid();
$this->assertFalse($result);
return $user;
}
}
And here is User.php class in app folder (in laravel 5.0 the architecture is different)
// app/User.php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Support\Facades\Validator;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
use Authenticatable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
public static $rules = [ 'name' => 'required|min:3' ];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
/**
* validate input
*
* #return bool
*/
public function isValid()
{
$validation = Validator::make($this->attributes, static ::$rules);
if ($validation->passes()) return true;
$this->errors = $validation->messages();
return false;
}
}
I noticed two problems with your code:
You said your test folder is
app/tests/models/UserTest.php
That is incorrect. In a clean install of Laravel 5.0 - the test class is in the base folder - not the app folder - so it should be
tests/models/UserTest.php
Also - your User is namespaced in Laravel 5.0 - so your code will need to be
$user = new \App\User;

Categories