DB Seeder class not found - php

I am trying to seed a database with the following files, 'ItemsTableSeeder' and 'UsersTableSeeder', but I keep on receiving the message: "Target class [ItemsTableSeeder] does not exist." when I run php artisan db:seed.
The files were added in the command prompt with the commands 'php artisan make:seeder ItemsTableSeeder' and 'php artisan make:seeder UsersTableSeeder'.
Here's the structure of my files:
-database
-- factories
ItemFactory.php
UserFactory.php
-- seeders
DatabaseSeeder.php
ItemsTableSeeder.php
UsersTableSeeder.php
// ItemsTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class ItemsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(\App\Items::class, 20)->create();
}
}
// UsersTableSeeder.php
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
factory(\App\Users::class, 3)->create();
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call('ItemsTableSeeder');
$this->call('UsersTableSeeder');
}
}
I have tried running 'composer dump-autoload' after adding the two seeder files, but at this stage this is not making any difference. I have also tried clearing the cache 'php artisan config:cache'.
Here is an extract from my 'autoload_classmap.php' (after running composer dump-autoload):
'Cron\\HoursField' => $vendorDir . '/dragonmantank/cron-expression/src/Cron/HoursField.php',
'Cron\\MinutesField' => $vendorDir . '/dragonmantank/cron-expression/src/Cron/MinutesField.php',
'Cron\\MonthField' => $vendorDir . '/dragonmantank/cron-expression/src/Cron/MonthField.php',
'Database\\Factories\\ItemFactory' => $baseDir . '/database/factories/ItemFactory.php',
'Database\\Factories\\UserFactory' => $baseDir . '/database/factories/UserFactory.php',
'DeepCopy\\DeepCopy' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/DeepCopy.php',
'DeepCopy\\Exception\\CloneException' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Exception/CloneException.php',
'DeepCopy\\Exception\\PropertyException' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Exception/PropertyException.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineCollectionFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineCollectionFilter.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineEmptyCollectionFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineEmptyCollectionFilter.php',
'DeepCopy\\Filter\\Doctrine\\DoctrineProxyFilter' => $vendorDir . '/myclabs/deep-copy/src/DeepCopy/Filter/Doctrine/DoctrineProxyFilter.php',
Any ideas of other things to try would be greatly appreciated,
Thanks,
Robert
London, England

add namespace Database\Seeders; at top of each seeder files
Then composer dump-autoload

Your structure files working good.
Try to fresh migrite
php artisan migrate:fresh --seed
if still not fixed try this: php artisan db:seed --force
then:
1- composer dump-autoload
2- php artisan db:seed
let me know if that work

Have you tried add namespace Database\Seeders; before run command?

Probably you forget to import Users model.
For example:
database\seeders\UsersSeeder.php
namespace Database\Seeders;
use App\Models\Users;
use Illuminate\Database\Seeder;

Related

Illuminate\Contracts\Container\BindingResolutionException : Target class [Database\Seeders\PermissionTableSeeder] does not exist

So I have a problem with seeding, the first time I got this error I thought maybe the name of the file and the table is not the same. I tried looking it up and what I found was from this link in laravel 8 with seeding , i has this issue Target class [TableSeeder] does not exist and it says to edit the namespace from Database\Seeds to Database\Seeders but that's not the problem because it's already correct. It says to check the composer.json for autoload and change Seeds to Seeders...
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
but I also have the exact same thing as they suggested. And after that some people also suggested doing composer dump-autoload and this is the result....
Generating optimized autoload files
Class App\Http\Requests\UpdaUserRequest located in \app\Http\Requests\UpdateUserRequest.php does not comply with psr-4 autoloading standard. Skipping.
> Illuminate\Foundation\ComposerScripts::postAutoloadDump
> #php artisan package:discover --ansi
INFO Discovering packages.
jenssegers/agent ............................ DONE
laravel/fortify ............................. DONE
laravel/jetstream ........................... DONE
laravel/sail ................................ DONE
laravel/sanctum ............................. DONE
laravel/tinker .............................. DONE
livewire/livewire ........................... DONE
nesbot/carbon ............................... DONE
nunomaduro/collision ........................ DONE
nunomaduro/termwind ......................... DONE
spatie/laravel-ignition ..................... DONE
Generated optimized autoload files containing 5496 classes
And I tried to seed it again and it gave me this....
php artisan db:seed
INFO Seeding database.
Illuminate\Contracts\Container\BindingResolutionException
Target class [Database\Seeders\PermissionTableSeeder] does not exist.
at \vendor\laravel\framework\src\Illuminate\Container\Container.php:877
873▕
874▕ try {
875▕ $reflector = new ReflectionClass($concrete);
876▕ } catch (ReflectionException $e) {
If anyone can help me, I am very grateful for anyone that can help. This is my DatabaseSeeder.php...
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([
PermissionTableSeeder::class,
RolesTableSeeder::class,
PermissionRoleTableSeeder::class,
UsersTableSeeder::class,
RoleUsersTableSeeder::class,
]);
}
}
and this is the PermissionsTableSeeder.php....
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class PermissionsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$permissions = [
[
'id' => 1,
'title' => 'user_access',
],
[
'id' => 2,
'title' => 'task_access',
],
];
Permissions::insert($permissions);
}
}
I got the answer, so first of all apparently the name for table seeder is not right. And then I got this error...
Error
Class "Database\Seeders\permissions" not found
at \database\seeders\PermissionsTableSeeder.php:28
24▕ 'title' => 'task_access',
25▕ ],
26▕ ];
27▕
➜ 28▕ permissions::insert($permissions);
29▕ }
30▕ }
31▕
and after I scour through the internet I found this https://laracasts.com/discuss/channels/laravel/laravel-8-class-databaseseedersdb-not-found. So I read the answer so you need to add use Illuminate\Support\Facades\DB; in your table seeder so it can call the database to get it to work. So now my PermissionsTableSeeder.php looks like this and it works just fine.
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class PermissionsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$permissions = [
[
'id' => 1,
'title' => 'user_access',
],
[
'id' => 2,
'title' => 'task_access',
],
];
DB::table('permissions')->insert($permissions);
}
}

why my cron job is not working in laravel?

in db i have column visit_clear i want it 0 after one day so i used this code
in kernal.php
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected $commands = [
];
protected function schedule(Schedule $schedule)
{
$schedule->command('cron:update-user-not-new')->daily();
}
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
and in command/UpdateUserNotNew.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class UpdateUserNotNew extends Command
{
protected $signature = 'cron:update-user-not-new';
protected $description = 'Command description';
public function __construct()
{
parent::__construct();
}
public function handle()
{
$dayAgo = 1; // Days ago
$dayToCheck = \Carbon\Carbon::now()->subDays($dayAgo)->format('Y-m-d');
Customer::whereDate('visit_date', '<=', $dayToCheck)
->update([
'visit_clear' => 0
]);
}
}
i am sheduling commnd like this as u can see cron:update-user-not-new should i use crone:UpdateUserNotNew?
You need to register your command in Kernel.php like this:
protected $commands = [
'App\Console\Commands\UpdateUserNotNew',
];
You should then be able to run the command manually with php artisan cron:update-user-not-new
In order for the automatic running of the command to work, you need to add an entry to your system's task scheduler, as this is what Laravel uses to run commands on a schedule.
Assuming you are using Linux, you need to add an entry to your crontab. To do this, in a command prompt enter crontab -e, hit enter, and add this line:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Don't forget to replace /path-to-your-project with the root folder of your project
Once done editing the crontab, save and close the editor and the new entries should be installed, and your command should now run on the schedule.
All this info came from https://laravel.com/docs/7.x/scheduling so if you need more info take a look there

How can I schedule the pinging of routes within my application [duplicate]

In kohana framework I can call controller via command line using
php5 index.php --uri=controller/method/var1/var2
Is it possible to call controller I want in Laravel 5 via cli? If yes, how to do this?
There is no way so far (not sure if there will ever be). However you can create your own Artisan Command that can do that. Create a command CallRoute using this:
php artisan make:console CallRoute
For Laravel 5.3 or greater you need to use make:command instead:
php artisan make:command CallRoute
This will generate a command class in app/Console/Commands/CallRoute.php. The contents of that class should look like this:
<?php namespace App\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Illuminate\Http\Request;
class CallRoute extends Command {
protected $name = 'route:call';
protected $description = 'Call route from CLI';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$request = Request::create($this->option('uri'), 'GET');
$this->info(app()['Illuminate\Contracts\Http\Kernel']->handle($request));
}
protected function getOptions()
{
return [
['uri', null, InputOption::VALUE_REQUIRED, 'The path of the route to be called', null],
];
}
}
You then need to register the command by adding it to the $commands array in app/Console/Kernel.php:
protected $commands = [
...,
'App\Console\Commands\CallRoute',
];
You can now call any route by using this command:
php artisan route:call --uri=/route/path/with/param
Mind you, this command will return a response as it would be sent to the browser, that means it includes the HTTP headers at the top of the output.
I am using Laravel 5.0 and I am triggering controllers using this code:
$ php artisan tinker
$ $controller = app()->make('App\Http\Controllers\MyController');
$ app()->call([$controller, 'myMethodName'], []);
the last [] in the app()->call() can hold arguments such as [user_id] => 10 etc'
For Laravel 5.4:
php artisan make:command CallRoute
Then in app/Console/Commands/CallRoute.php:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Http\Request;
class CallRoute extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'route:call {uri}';
/**
* The console command description.
*
* #var string
*/
protected $description = 'php artsian route:call /route';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$request = Request::create($this->argument('uri'), 'GET');
$this->info(app()->make(\Illuminate\Contracts\Http\Kernel::class)->handle($request));
}
}
Then in app/Console/Kernel.php:
protected $commands = [
'App\Console\Commands\CallRoute'
];
Call like: php artisan route:call /path
Laravel 5.7
Using tinker
// URL: http://xxx.test/calendar?filter[id]=1&anotherparam=2
$cc = app()->make('App\Http\Controllers\CalendarController');
app()->call([$cc, 'getCalendarV2'], ['filter[id]'=>1, 'anotherparam' => '2']);
You can do it in this way too. First, create the command using
php artisan command:commandName
Now in the handle of the command, call the controller and trigger the method.
Eg,
public function handle(){
$controller = new ControllerName(); // make sure to import the controller
$controller->controllerMethod();
}
This will actually do the work. Hope, this helps.
DEPENDENCY INJECTION WON'T WORK
To version 8 of laravel.
First step: type command in terminal
php artisan tinker
Secound step:
$instante = new MyController(null);
Or if argument by an instance of model, then, pass name model class.
Example:
$instante = new MyController(new MyModelHere());
Press enter.
Finally, call method with $instante->myMethod() here.
See:

Laravel Seeding missing classes

I am following this tutorial until I need to generate seeds using: php artisan db:seed. It always said that my Article and User class are not found.
I have looking for solution like in:
https://laracasts.com/discuss/channels/lumen/unable-to-run-php-artisan-dbseed-due-to-missing-class (setting up composer.json's auto load paths and composer dump-autoload)
Laravel cannot find class of a package
I have deleting my vendor folder and do composer install again
Also importing the file manually, require_once with relative path to the model from the seeding or root of the projet, but neither works.
I think this should work out-of-the-box but it isn't. What is my problem? And what is my solution?
EDIT 1: Someone requested seeders codes here you are!
Article Seeder
<?php
use Illuminate\Database\Seeder;
class ArticlesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
// Let's truncate our existing records to start from scratch.
Article::truncate();
$faker = \Faker\Factory::create();
// And now, let us create a few articles in our database:
for ($i = 0; $i < 50; $i ++) {
Article::create([
'title' => $faker->sentence,
'body' => $faker->paragraph,
]);
}
}
}
User Seeder
<?php
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
// Let's clear the user table first
User::truncate();
$faker = \Faker\Factory::create();
// Let's make sure everyone has the same password and
// let's hash it before the loop, or else our seeder
// will be too slow.
$password = Hash::make('toptal');
User::create([
'name' => 'Administrator',
'email' => 'admin#test.com',
'password' => $password,
]);
// And now let's generate a few dozen users for our app:
for ($i = 0; $i < 10; $i ++) {
User:;create([
'name' => $faker->name,
'email' => $faker->email,
'password' => $password,
]);
}
}
}
Database Seeder
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$this->call(UsersTableSeeder::class);
$this->call(ArticlesTableSeeder::class);
}
}
First you should import the full class path, i.e.- App\User. Then regenerate the autoload file with- composer dump-autoload
You should either import the models that you've use so you can use just the Model's class name in your code or use the fully qualified name of the Model.
E.g., instead of just User, use App\User.
Use imports if you think you will have many instance where you will use the User class name, to avoid the hassle of typing the fully qualified name.
<?php
...
use App\User;
...
$users = User::all(); // <-- now you can do this.
I followed the same tutorial. Just add a line "use App\Article;" so that your class will find the appropriate class.
Its like including a header file path in c/c++.

Laravel 5.5 Model not found in Seed class

I have been around this problem for so long and cannot solve it... I found several people with (apparently) the same problem as me, but any of the answers helped me.
I have the following "Sector.php" inside "app" folder:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Sector extends Model
{
protected $table = 'sectors';
protected $fillable = ['name'];
protected $guarded = ['id'];
public function services()
{
return $this->belongsToMany('App\Service', 'services_sectors', 'sector_id', 'service_id');
}
public function observations()
{
return $this->belongsToMany('App\Observation', 'observations_sectors', 'sector_id', 'observation_id');
}
}
And the following "DatabaseSeeder.php" inside "database/seeds":
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('sectors')->delete();
Sector::create(['name' => 'Health']);
$this->command->info('Sectors table seeded');
}
}
So, when I access my server I run the command php artisan db:seed but I have the following error:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Sector' not found
I have been trying ./composer update, ./composer dump-autoload -o, changing Sector to App\Sector in the seeder file but the error just changes to Class 'App\Sector' not found.
If I add use App\Sector; to the top of the Seeder file the error is the same.
It seems I tried all the solutions that are online, so maybe I have some configuration done incorrectly? Any suggestions on this?
Try adding use App\Sector; to your seeding file.
Once you have it working, think about separating your seeding files into their separate classes. It is much easier to maintain that way.
Generate Seeder File
First, in terminal, generate a new seed file:
php artisan make:seeder SectorsTableSeeder
Transfer your seeding code into the run method of this new file.
Call seeder files
Then, modify the DatabaseSeeder.php file to run the SectorsTableSeeder class. For example:
public function run()
{
$this->call(SectorsTableSeeder::class);
}
Update
Sorry, I missed that part.
This is what I would try:
$now = date('Y-m-d H:i:s');
public function run()
{
DB::table('sectors')->delete();
DB::table('sectors')->insert([
'name' => 'Health',
'created_at' => $now,
'updated_at' => $now,
]);
$this->command->info('Sectors table seeded');
}

Categories