LARAVEL 8: Class 'Database\Seeders\DB' not found - php

I'm working with seeder to fill my users table, so I created a new seeder called UserSeeder and then I added these codes to it:
public function run()
{
foreach(range(1,10) as $item)
{
DB::table('users')->insert([
'name' => "name $item",
'email' => "email $item",
'email_verified_at' => now(),
'password' => "password $item"
]);
}
}
After that I tried php artisan db:seed --class=UserSeeder but it shows me:
Error
Class 'Database\Seeders\DB' not found
which is related to this line:
DB::table('users')->insert([
So why it is not found there, what should I do now?

That's because Laravel will look for DB class in the current namespace which is Database\Seeders.
Since Laravel has facades defined in config/app.php which allows you to use those classes without full class name.
'DB' => Illuminate\Support\Facades\DB::class,
You can either declare DB class after the namespace declaration with
use DB;
or just use it with backslash.
\DB::table('users')->insert([

In the UserSeeder Class add:
use Illuminate\Support\Facades\DB;

I have fixed same error in Laravel 9 by importing
use Illuminate\Database\Seeder;

Related

factory not being found in PHP Feature Test Laravel-8

Just playing around with laravel-8 unit tests. I extended the basic TestCase and thought laravels factory method would be available. I checked the composer.json and the factories are being loaded.
I am trying to run this particular test but factory is not found any ideas:
<?php
namespace Tests\Feature\Http\Controllers\Auth;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use App\User;
class LoginControllerTest extends TestCase
{
use RefreshDatabase;
/** #test */
public function login_authenticates_and_redirects_user()
{
$user = factory(User::class)->create();
$response = $this->post(route('login'), [
'email' => $user->email,
'password' => 'password'
]);
$response->assertRedirect(route('home'));
$this->assertAuthenticatedAs($user);
}
}
The error I am getting is:
1) Tests\Feature\Http\Controllers\Auth\LoginControllerTest::login_authenticates_and_redirects_user
Error: Call to undefined function Tests\Feature\Http\Controllers\Auth\factory()
On laravel 8 models are at 'App\Models\'.
It changes how factory works. See at docs.
So, it should be like:
<?php
namespace Tests\Feature\Http\Controllers\Auth;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;
use App\Models\User;
class LoginControllerTest extends TestCase
{
use RefreshDatabase;
/** #test */
public function login_authenticates_and_redirects_user()
{
$user = User::factory->create();
$response = $this->post(route('login'), [
'email' => $user->email,
'password' => 'password'
]);
$response->assertRedirect(route('home'));
$this->assertAuthenticatedAs($user);
}
}
Turns out in upgrading to laravel-8 release notes:
https://laravel.com/docs/8.x/upgrade#seeder-factory-namespaces
"Laravel's model factories feature has been totally rewritten to support classes and is not compatible with Laravel 7.x style factories."
So in order to make it work I used:
$user = \App\Models\User::factory(User::class)->make();

eloquent relations with extend user model sentinel laravel package

I have a class User that extends
<?php
namespace App;
class User extends \Cartalyst\Sentinel\Users\EloquentUser
{
public function chalets(){
return $this->hasMany('App\Chalet');
}
}
and i have Chalet Class
class Chalet extends Model
{
protected $fillable = [
'name', 'description',
];
public function user(){
return $this->belongsTo('App\User');
}
}
And i have method to add chalet by user :
public function postCreateChalet(Request $request){
$chalet = new Chalet([
'name' => $request->input('name'),
'description' => $request->input('description')
]);
Sentinel::getUserRepository()->setModel('App\User');
$user = Sentinel::getUser();
$user->chalets()->save($chalet);
return ('chalet has created');
}
and its give me an error :
BadMethodCallException
Call to undefined method Cartalyst\Sentinel\Users\EloquentUser::chalets()
Is it a right way to extend User class ?
I have searched for ways to extend the User class. I found this question:Model Inheritance in Laravel didn't help me though.
I'm using Laravel 5.7
The exception you're getting indicates Sentinel is still referring to the default stock Sentinel's EloquentUser model. Make sure you point to your extended user model with the published Sentinel configurations.
Run the below command
php artisan vendor:publish --provider="Cartalyst\Sentinel\Laravel\SentinelServiceProvider"
Open up the published config file at 'config\cartalyst.sentinel.php'
Modify it from the below content:
'users' => [
'model' => 'Cartalyst\Sentinel\Users\EloquentUser',
],
to:
'users' => [
'model' => 'App\User',
],
For more information, refer to https://github.com/cartalyst/sentinel/wiki/Extending-Sentinel
You won't need the following line after you configured it via config:
Sentinel::getUserRepository()->setModel('App\User');

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');
}

Laravel DB Seeder won't seed in console

Hi I have the following seeder class I am trying to seed. When I run the php artisan db:seed command the only thing that seeds is my previous seeder class I created a few weeks ago. I have no idea what I am missing. I inserted SoftDeletes and Protected fillables as well.
Here is my seeder class:
public function run()
{
DB::table('leave_type')->insert([
[
'leaveType' => 'Vacation Leave'
],
[
'leaveType' => 'Sick Leave'
],
[
'leaveType' => 'Afternoon Off'
],
[
'leaveType' => 'Special Leave'
],
[
'leaveType' => 'Study Leave'
],
]);
}
My model:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class LeaveType extends Model
{
protected $fillable = ['leaveType'];
protected $table ="leave_type";
use SoftDeletes;
public $timestamps = true;
}
Converting my comment to answer;
Make sure laravel knows about the new database seeder class you've generated by running this command:
composer dump-auto
Make sure your seeder class is registered in {PROJECT}/database/seeds/DatabaseSeeder.php like this:
$this->call(YourNewSeeder::class);
Then you could refresh the database (rollback all migration, re-run the migration) and run the seeder in one go with this command:
php artisan migrate:refresh --seed
or just run the specific seeder only like this:
php artisan db:seed --class=YourNewSeeder

Laravel 4 - Access Auth Class in Validation Class

I want to access the Auth Class within my ValidatorService Class.
namespace Services\Validators\User;
use \Services\Validators\Validator;
use \Illuminate\Support\Facades\Auth;
class Edit extends Validator {
public static $rules = [
'email' => 'required|unique:users,email,'.Auth::user()->id
];
}
I tried to use the \Illuminate\Support\Facades\Auth Namespace, but laravel throws an Exception.
Error: syntax error, unexpected '.', expecting ']'
Laravel only throws the exception, when I try to use Auth::user()->id.
If I remove Auth::user()->id and add a number, for example 1, it works.
I also tried to implement the Illuminate\Auth\UserInterface but it is not working.
How can I use the Auth Class in my ValidatorService Class?
EDIT: Problem solved -> Scroll down.
Solution:
You cannot use functions or variables when setting a variable on a
class.
Thanks to AndreasLutro on http://laravel.io/irc
So I removed the class variable and added a method.
Now everythings works fine.
Code:
class Edit extends Validator{
public static function rules(){
return array(
'email' => 'required|unique:users,email,'.Auth::user()->id
);
}
}
Cheers, Steven.
Try to surround the 'required|unique:users,email,'.Auth::user()->id
part with ( and ) so that it looks like this:
public static $rules = [
'email' => ('required|unique:users,email,' . Auth::user()->id)
];

Categories