Call database seeder from a subfolder - php

I want to create a set of database seed classes specifically for adding data for test cases I'm writing.
My plan was to put them in the folder:
app/database/seeds/testData/
and then call the seeder via the command:
php artisan db:seed --class="testData/myTestSeeder"
But I get a "class does not exist" error.
Is it possible to call database seeders that live in a subfolder in seeds? I don't see an explicit "yes" in the docs, but I don't see an explicit "no" either.

You shouldn't need to edit your classmap on your project, just make sure to run
composer dump-autoload
after moving your class to a subfolder.
Once you've done that, run this (no need to mention testData here)
php artisan db:seed --class="myTestSeeder"

You need to tell the autoloader how to load your new class. This is relatively simple; add the following to your composer.json in the classmap property:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php",
"app/database/seeds/testData" // <-- Add this
]
},
After that, run composer dump-autoload and your seed file should now be loaded successfully.

When you create new Seeder class, for example:
php artisan make:seeder Authorization/CreateAppRoleSeeder
As a result, get new class:
<?php
use Illuminate\Database\Seeder;
class Authorization/CreateAppRoleSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
You have to replace class Authorization/CreateAppRoleSeeder extends Seeder
with class CreateAppRoleSeeder extends Seeder.
Next, execute the dump composer command:
composer dump
After add class to file 'database\Seeder\DatabaseSeeder'
In my case, for example:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(CreateAppRoleSeeder::class);
}
}
After that execute the command
php artisan db:seed
In my case
php artisan db:seed --class=CreateAppRoleSeeder
So will work ;)

Related

Laravel 7 - artisan seed Target class [DatabaseSeeder] does not exist

I'm trying to seed my "DatabaseSeeder.php' But when I try to run
php artisan db:seed
I get the error:
Target class [DatabaseSeeder] does not exist.
My code in "DatabaseSeeder.php" looks like this:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
factory(App\User::class, 3)->create()->each(function($u) {
$u->questions()
->saveMany(
factory(App\Question::class, rand(1, 5))->make()
);
});
}
}
What I tried so far:
composer dump-autoload
php artisan cache:clear
php artisan optimize
Note: I don't have a User-Made seeder, I'm trying to use the default one (DatabaseSeeder.php), but for some reason, it's telling me that it doesn't exist.
With Laravel 7, the composer.json needs the classmap reference in the autoload mapping, because the default seed folder doesn't respect PSR-4: database/seeds (see Laravel Documentation - Database: Seeding)
Check to have this in the composer.json:
"classmap": [
"database/seeds",
"database/factories"
],
And run composer dump-autoload
See this similar error: Target class [DatabaseSeeder] does not exist - Laravel 7 and Composer 2

Target class [UsersTableSeeder] does not exist

I am using laravel latest version 7.
When I run php artisan db:seed I am getting the following error:
Illuminate\Contracts\Container\BindingResolutionException
Target class [UsersTableSeeder] does not exist.
After writing your seeder, you have to run composer dump-autoload
Make sure that you have this code in your composer.json:
"autoload": {
"classmap": [
"database"
],
}
The default laravel installation doesn't have UsersTableSeeder you need to create a new seeder by running
php artisan make:seeder UsersTableSeeder
Laravel doesnt have the UserTableSeeder by default. You can create one by running the following artisan command:
php artisan make:seeder UsersTableSeeder
After running the command you can find the seeder in the database directory.
In the run function of the seeder you can create the needed users.
The example below is for my RoleSeeder but it might provide some direction to a suitable solution:
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$customer = Role::updateOrCreate(['name' => 'customer']);
$customerPermissions = [
'view users',
'create users',
'edit users',
'delete users',
'view machines',
'view profile',
'edit profile',
'view documents',
];
$customer->givePermissionTo($customerPermissions);
}
I recommand using the updateOrCreate function just because in testing you might want to run a seeder multiple times. This function wil check if the record already exists and will update the record accordingly

Lumen 5.6 - php artisan db:seed got error 'Class DatabaseSeeder does not exist'

I'm trying to seed with Lumen 5.6.3 and executed the command:
php artisan db:seed.
Then I got error, saying
In Container.php line 767:
Class DatabaseSeeder does not exist
In my database/seeds directory, DatabaseSeeder.php does exist.
I've just copied the source in Lumen's official document and the source is like below.
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
//
}
}
I've googled many times to solve this error and of course tried composer dump-autoload, composer dump-autoload -o, composer dump-autoload --no-dev several times and the situation has never changed.
I also checked my composer/autoload_classmap.php and there is 'DatabaseSeeder' => $baseDir . '/database/seeds/DatabaseSeeder.php' so I looks like autoload does work correctly.
I really appreciate any advices or comments.
Thank you.
To fix this issue, you have to tweak your composer.json in order for
php artisan db:seed
to work
By default, Lumen has placed the database directory under autoload-dev.
"autoload-dev": {
"classmap": [
"tests/",
"database/"
]
},
To solve this, simple put the classmap together with your database directory under autoload
"autoload": {
"psr-4": {
"App\\": "app/"
},
"classmap": [
"database/"
]
},
after tweaking run composer update command in order for the tweak to work.
You can use php artisan db:seed with lumen.
The command is: php artisan make:seeder Seedername.
For example you can use php artisan make:seeder UsersTableSeeder to create table seeder for the user.
The file will be created in the folder database\seeds.
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(App\User::class, 10)->create();
}
}
This will create 10 example for the user class.
Then you should cinfigure the databaseseeder file
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
// Register the user seeder
$this->call(UsersTableSeeder::class);
Model::reguard();
}
}
I set a wrong value for bootstrap/app.php.
I set like the below.
require_once __DIR__.'/../../vendor/autoload.php';
After I modified this part like following, I could run db:seed command correctly.
require_once __DIR__.'/../vendor/autoload.php';

PhpStorm - Some warnings on Laravel facades

I make right usage of Laravel's facades and PhpStorm gives me warnings, why is that?
And on image I pointed "x" for some...types of data? In functions I use, why do I have these? How to remove them?
Using facades with Laravel
Luke Waite is right:
You're not using facades. You've imported the classes, and on the
first, Categories, the IDE is telling you that the get method is not a
static method.
Just import the facade instead (if it exist).
See the documentation on Facades to learn more on how to use the available facades and how to define your own.
A facade class should look like this:
use Illuminate\Support\Facades\Facade;
class Cache extends Facade
{
/**
* Get the registered name of the component.
*
* #return string
*/
protected static function getFacadeAccessor()
{
return 'cache';
}
}
Where the 'cache' string is the name of a service container binding and defined in a service provider, something like this:
use App\Cache\MyCache;
use Illuminate\Support\ServiceProvider;
class CacheServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
$this->app->singleton('cache', function ($app) {
return new MyCache();
});
}
}
Fixing the warnings with Facades
That being said, I was tired of the warnings and the missing auto-completion and highlighting with facades so I also searched to find a way to fix these.
I came upon laravel-ide-helper which adds Laravel CLI commands that generates php files that only serves to be parsed by your IDE.
Install
Require this package with composer using the following command:
composer require barryvdh/laravel-ide-helper
After updating composer, add the service provider to the providers
array in config/app.php
Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, To
install this package on only development systems, add the --dev flag
to your composer command:
composer require --dev barryvdh/laravel-ide-helper
In Laravel, instead of adding the service provider in the
config/app.php file, you can add the following code to your
app/Providers/AppServiceProvider.php file, within the register()
method:
public function register()
{
if ($this->app->environment() !== 'production') {
$this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}
// ...
}
This will allow your application to load the Laravel IDE Helper on
non-production enviroments.
Automatic phpDoc generation for Laravel Facades
You can now re-generate the docs yourself (for future updates)
php artisan ide-helper:generate
Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating (and php artisan
optimize after).
You can configure your composer.json to do this after each commit:
"scripts":{
"post-update-cmd": [
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"php artisan ide-helper:generate",
"php artisan ide-helper:meta",
"php artisan optimize"
]
},
The .phpstorm.meta.php and _ide_helper.php files will be generated and should be added to your .gitignore as you don't want to commit these.

Laravel 5: DB Seed class not found

I have this DatabaseSeeder.php:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('MemberInvitationSeeder');
}
}
I have this file MemberInvitationSeeder.php, sibling to the DatabaseSeeder.php file
<?php
use Illuminate\Database\Seeder;
use App\MemberInvitation;
class MemberInvitationSeeder extends Seeder {
public function run()
{
MemberInvitation::truncate();
MemberInvitation::create( [
'id' => 'BlahBlah' ,//com_create_guid(),
'partner_id' => 1,
'fisrt_name' => 'Thats',
'last_name' => 'Me',
'email' => 'me#mymail.com',
'mobile_phone' => '444-342-4234',
'created_at' => new DateTime
] );
}
}
Now I call
php artisan db:seed
and I get:
[ReflectionException]
Class MemberInvitationSeeder does not exist
I tried everything I could find including "composer dump-autoload". to no avail. What am I doing wrong?
Step one - generate seed:
php artisan make:seed MemberInvitationSeeder
Step two - In DatabaseSeeder.php add line:
$this->call(MemberInvitationSeeder::class);
Step three:
composer dump-autoload
Step four:
php artisan db:seed
This should work
If this isn't the clue, check the composer.json file and make sure you have code below in the "autoload" section:
"classmap": [
"database"
],
I solved this by adding the class to the seeder file, with the instruction use:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\YourClassName;
I believe I know the reason now.
The new class MemberInvitationSeeder wasn't in the autoloaded classes in the composer.json file.
It wasn't there because I added that class manually.
Now, going forward, if I add such classes again, what should I use in order for my class to automatically to the autoloader?
This work for me
composer dump-autoload
php artisan db:seed
I ran into the similar error but I was using DB facade DB::table rather than model. I am posting the answer just in case somebody has similar issues.
The seeder file had namespace namespace Database\Seeders; and laravel was trying to look for DB class inside the namespace and hence the error appeared.
Class 'Database\Seeders\DB' not found.
Resolutions:
Remove the namespace and run composer dump-autoload
OR Add a backslash to \DB::table('stock_categories')->([ ... ]); so Laravel starts looking the DB facade from root (not from the namespace specified)
Eg,
\DB::table('MemberInvitation')->insert( [
'id' => 'BlahBlah' ,//com_create_guid(),
'partner_id' => 1,
'fisrt_name' => 'Thats',
'last_name' => 'Me',
'email' => 'me#mymail.com',
'mobile_phone' => '444-342-4234',
'created_at' => new DateTime
] );
If the above solutions doesn't work, try this one.
You may have changed the namespace (by default, it's "App").
What you need to do is to go to the composer.json file and check this:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
}
},
If the namespace is App like this example, this solution is not for you.
Otherwise, take the namespace you found and insert that line into your seeder class:
use NameSpaceFound\User;
You should include namespace if you want to use a string as a parameter
$this->call('Database\Seeders\MemberInvitationSeeder');
After making php artisan make:seed SeederName
then you need to run composer dump-autoload command after that
php artisan db:seed It is working for me.
I was facing this problem with laravel package with spatie
to solve this problem just
1- append seeders path in composer.json of your package
"autoload": {
"psr-4": {
...
"{packagename}\\{vendorname}\\Database\\Seeders\\": "database/seeders"
}
},
then go to your main project and update composer with composer update
auto-load your classess with composer dump-autoload
If it doesn't work delete Vendor folder and run composer install

Categories