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
Related
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
I have a cloned laravel application but when I try to generate a APP_KEY via php artisan key:generate it gives me an error:
In EncryptionServiceProvider.php line 42:
No application encryption key has been specified.
Which is obvious because that is exactly what I'm trying to create. Does anybody know how to debug this command?
update: Kind of fixed it with this post laravel 4: key not being generated with artisan
If I fill APP_KEY in my .env file php artisan key:generate works. But a newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
For some reason php artisan key:generate thinks it needs a app_key when it doesn't. It won't do any other commands either, they all error "No application encryption key has been specified."
php artisan key:generate needs an existing key to work. Fill the APP_KEY with 32 characters and rerun the command to make it work.
Edit: A newly created app via laravel new with a deleted APP_KEY can run php artisan key:generate without issue for some reason.
Edit a year later:
The real problems lays in 2 added provider services. The boot() functions are badly written which causes the problem. Still not exactly sure why it doesn't work but I'll try and figure it out for somebody who may have the same problem later.
The two files in question
<?php
namespace App\Providers;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class ResponseServiceProvider extends ServiceProvider
{
public function boot(ResponseFactory $factory){
parent::boot();
$factory->macro('api', function ($data=null, $code=null, $message=null) use ($factory) {
$customFormat = [
'status' => 'ok',
'code' => $code ? $code : 200,
'message' => $message ? $message : null,
'data' => $data
];
if ($data instanceof LengthAwarePaginator){
$paginationData = $data->toArray();
$pagination = isset($paginationData['current_page']) ? [
"total" => $paginationData['total'],
"per_page" => (int) $paginationData['per_page'],
"current_page" => $paginationData['current_page'],
"last_page" => $paginationData['last_page'],
"next_page_url" => $paginationData['next_page_url'],
"prev_page_url" => $paginationData['prev_page_url'],
"from" => $paginationData['from'],
"to" => $paginationData['to']
] : null;
if ($pagination){
$customFormat['pagination'] = $pagination;
$customFormat['data'] = $paginationData['data'];
}
}
return $factory->make($customFormat);
});
}
public function register(){
//
}
}
<?php
namespace App\Providers;
use App\Http\Controllers\Auth\SocialTokenGrant;
use Laravel\Passport\Bridge\RefreshTokenRepository;
use Laravel\Passport\Bridge\UserRepository;
use Laravel\Passport\Passport;
use Laravel\Passport\PassportServiceProvider;
use League\OAuth2\Server\AuthorizationServer;
/**
* Class CustomQueueServiceProvider
*
* #package App\Providers
*/
class SocialGrantProvider extends PassportServiceProvider{
/**
// * Bootstrap any application services.
// *
// * #return void
// */
public function boot(){
parent::boot();
app(AuthorizationServer::class)->enableGrantType($this->makeSocialRequestGrant(), Passport::tokensExpireIn());
}
/**
* Register the service provider.
*
* #return void
*/
public function register(){
}
/**
* Create and configure a SocialTokenGrant based on Password grant instance.
*
* #return SocialTokenGrant
*/
protected function makeSocialRequestGrant(){
$grant = new SocialTokenGrant(
$this->app->make(UserRepository::class),
$this->app->make(RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}
}
php artisan key:generate is a command that create a APP_KEY value in your .env file.
When you run composer create-project laravel/laravel command it will generate a APP_Key in .env file, but when you checkout a new branch by git or clone a new project, the .env file will not include, so you have to run artisan key:generate to create a new APP_KEY.
You changed your question. In this case, you can try it.
php artisan key:generate
php artisan config:cache
If you don't have a vendor folder then,
1) Install composer dependencies
composer install
2) An application key APP_KEY need to be generated with the command
php artisan key:generate
3) Open Project in a Code Editor, rename .env.example to .env and modify DB name, username, password to your environment.
4) php artisan config:cache to effect the changes.
check your .env file. Is it exists?
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';
I do everything by-the-book:
Installed fresh Laravel 5.3.9 app (all my non-fresh apps produce the same error)
run php artisan make:auth
create migrations for a new table
`php artisan make:migration create_quotations_table --create=quotations
Schema::create('quotations', function (Blueprint $table) {
$table->increments('id');
$table->string('text');
// my problem persists even with the below two columns commented out
$table->integer('creator_id')->unsigned()->index('creator_id');
$table->integer('updater_id')->unsigned()->index('updater_id');
$table->softDeletes();
$table->timestamps();
});
Then I run php artisan migrate
Then I define a new seed php artisan make:seeder QuotationsTableSeeder
The complete content of the file, after I add a simple insert:
<?php
use Illuminate\Database\Seeder;
class QuotationsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('quotations')->insert([
'text' => str_random(10),
]);
}
}
Then I run php artisan db:seed
problem
it simply doesn't work. No feedback presented, no errors in log file.
The probem persists in both my local environment (Win7, newest WAMP server)
and my Digital Ocean VPS powered by Ubuntu 16.04.
All the above steps I took in several separate apps - for no result. Also under Laragon 2.0.5 server.
what I have tried
php artisan optimize as suggested here.
composer dump-autoload i php artisan clear-compiled also have brought no results
I also tried to seed just following the official docs example - failed.
I added use DB; to the seed file - still no result.
to do
help!!! How come they don't work?
Are you calling your seeder inside the DatabaseSeeder class? This way:
database/seeds/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(QuotationTableSeeder::class);
}
}
Or, add the --class option when using the php artisan db:seed command, this way:
php artisan db:seed --class="QuotationTableSeeder"
After creating or removing your seeders, don't forget to run the following command:
composer dump-autoload
NB:
Please use with caution on DEV ENVIRONMENT and/or DISPOSABLE DATABASES ONLY
If anybody else is having issues with migrating AND seeding at the same time, please try
php artisan migrate:fresh --seed
Worked for me..
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 ;)