So I'm trying a basic php artisan db:seed after migrating my database but it keeps returning the title error in cmd -[Symfony\Component\Debug\Exception\FatalErrorException] Class 'User' not found
Things I Have Tried
php dump-autoload after updating the class
php dump-autoload before running the db:seed function
rolling back the migration and then re-running it
rolling back the migration and then re-running it with the --seed syntax
Change the namespace of the 'Users' File
Below is the migrations
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
I believe that everything here is correct, and now here is the user class.
<?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;
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'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
}
And now lastly is the all important database seeder
<?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('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John#doe.com']);
}
}
So that's it my full syntax, if any more files are required then please request them and I will update my question.
In your DatabaseSeeder in the root namespace you call the Class User. It therefor tries to load the class User. The definition of your class User is however in namespace App. You should therefor use either App\User in your DatabaseSeeder or add at the top of the file use App\User;
DatabaseSeeder
<?php
use App\User;
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('UserTableSeeder');
$this->call('UserTableSeeder');
Model::reguard();
}
}
class UserTableSeeder extends Seeder
{
public function run()
{
DB::table('users')->delete();
User::create(['email' => 'John#doe.com']);
}
}
Since Laravel 8+ the User class is now stored by default in the app/Models directory; so instead of using App\User use App\Models\User above.
Ps. by default Laravel ships with a User model, use that one. In case you removed that model you can use the fallback provided by Laravel:
use Illuminate\Foundation\Auth\User;
On a side note something I find very useful in order to debug artisan output. You should use the flag -vvv which adds extreme verbosity to the output messages including a complete stack trace.
php artisan migrate -vvv
Related
I have a new Laravel 9 application and I am trying to use Keycloak as an SSO.
I am using this package to achieve that. I created the migrations and the seeders to have some data. I am using my own user model extending the KeycloakUser provided by the package.
My seeder does not run and I get this error message:
Call to undefined method App\Models\User::create()
My Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Vizir\KeycloakWebGuard\Models\KeycloakUser;
class User extends KeycloakUser
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'firstname',
'surname',
'email',
'role',
];
/**
* Get the company that owns the user.
*/
public function company()
{
return $this->belongsTo(Company::class);
}
/**
* Get the comments for the user.
*/
public function comments()
{
return $this->hasMany(Comment::class);
}
}
The migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('firstname');
$table->string('surname');
$table->string('email')->unique();
$table->unsignedBigInteger('company_id')->nullable();
$table->enum('role', ['user', 'admin', 'superadmin'])->default('user');
$table->rememberToken();
$table->timestamps();
$table->foreign('company_id')->references('id')->on('companies');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
The seeder
<?php
namespace Database\Seeders;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
User::create([
'firstname' => 'Aaaa',
'surname' => 'Bbbb',
'email' => 'ab#first.com',
'role' => 'superadmin',
]);
}
}
What you can try to do is copy KeycloakUser into app\Models.
Rename the file and class to User and than add extends Model.
namespace Vizir\KeycloakWebGuard\Models;
use Auth;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
....
// all of these methods are originated from KeycloakUser
And dont forget to adjust your config/auth.php
'providers' => [
'users' => [
'driver' => 'keycloak-users',
'model' => App\Models\User::class,
],
// ...
]
I'm new to laravel and trying to make two tables with a one (customer) to many(table) relation and a custom Foreign Key tables.customer(I can not change this)
The connection is over customers.id on tables.customer.
After Running php artisan migrate:fresh --seed everything is created as expected. But tables.customer is always 0.
I don't get any errors. And both tables are created correctly.
What do I miss?
Here are my settings:
Models:
Customers.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model {
use HasFactory;
public function tables() {
return $this->hasMany(Tables::class, 'customer');
}
public $timestamps = false;
}
Tables.php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tables extends Model {
use HasFactory;
public function customers() {
return $this->belongsTo(Customers::class, 'customer');
}
public $timestamps = false;
}
Migration:
customers
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('customers', function (Blueprint $table) {
$table->string('id', 6)->primary();
$table
->string('img', 23)
->nullable()
->default(null);
$table->tinyText('name');
$table->tinyInteger('active')->default(1);
$table->bigInteger('created'); // unix timestamp when created
$table
->bigInteger('status')
->nullable()
->default(null); // null not deleted / unix timestamp when deleted
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('customers');
}
};
tables
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('tables', function (Blueprint $table) {
$table->string('id', 8)->primary();
$table->tinyText('number');
$table->string('customer', 6); // TODO: repalce with uuid
$table->bigInteger('created'); // unix timestamp when created
$table
->bigInteger('status')
->nullable()
->default(null); // null not deleted / unix timestamp when deleted
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('tables');
}
};
Factories:
CustomersFactory.php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Customers>
*/
class CustomersFactory extends Factory {
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition() {
return [
'id' => $this->faker->unique()->regexify('[A-Za-z0-9]{6}'),
'name' => $this->faker->company(),
'active' => $this->faker->boolean(),
'created' => $this->faker->unixTime(),
'status' => $this->faker->boolean() ? null : $this->faker->unixTime(),
];
}
}
TablesFactory.php
namespace Database\Factories;
use App\Models\Customers;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* #extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Tables>
*/
class TablesFactory extends Factory {
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition() {
return [
'id' => $this->faker->unique()->regexify('[A-Za-z0-9]{8}'),
'number' => $this->faker->unique()->numberBetween(1, 1000),
'customer' => Customers::factory()->create()->id,
'created' => $this->faker->unixTime(),
'status' => $this->faker->boolean() ? null : $this->faker->unixTime(),
];
}
}
Seeders:
customersSeeder.php
namespace Database\Seeders;
use App\Models\Customers;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class CustomersSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run() {
Customers::factory()
->count(10)
->hasTables(20)
->create();
}
}
TablesSeeder.php
namespace Database\Seeders;
use App\Models\Tables;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class TablesSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run() {
//
}
}
DatabaseSeeder.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([CustomersSeeder::class]);
}
}
Your issue is that you did not tell each model that the id is not an integer, it is by default (check the source code).
So add this to both models:
protected $keyType = 'string';
public $incrementing = false;
Read about that here.
By inspecting your models, you are recommended to define the table name first.
// ========== SPECIFY TABLE TO USE (https://stackoverflow.com/a/51746287/19250775) ========== //
protected $table = "users";
And then you need to define fillable properties in order to mass assign your database, as the docs said.
// ========== MASS ASSIGNABLE ATTRIBUTES ========== //
protected $fillable =
[
'id',
'name',
'email',
];
Or if you want every column becomes fillable just add guarded attribute.
protected $guarded = [];
I have a problem while attempting to seed my pivot table in database in Laravel. I get error
Base table or view not found: 1146 Table 'user_cuisines' doesn't exist
And my table name is actually user_cuisine, so it is like for some reason laravel doesn't show that table. I added in my relationships that user_cuisine is pivot table because of alphabet order. Any help is appreciated. Here is my code.
UserCuisineTableSeeder.php
<?php
use App\UserCuisine;
use App\UserProfile;
use Illuminate\Database\Seeder;
class UserCuisineTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$cuisines = UserCuisine::all();
UserProfile::all()->each(function ($userProfile) use ($cuisines) {
$userProfile->cuisines()->attach(
$cuisines->random(rand(1, 12))->pluck('id')->toArray()
);
});
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(WhitelabelTableSeeder::class);
$this->call(CitiesTableSeeder::class);
$this->call(UserTableSeeder::class);
$this->call(UserProfilePropertiesSeeder::class);
$this->call(UserProfileTableSeeder::class);
$this->call(FieldTableSeeder::class);
$this->call(FieldValueTableSeeder::class);
$this->call(CuisineTableSeeder::class);
$this->call(LiteratureTableSeeder::class);
$this->call(MusicTableSeeder::class);
$this->call(SportTableSeeder::class);
$this->call(TvTableSeeder::class);
$this->call(UserCuisineTableSeeder::class);
$this->call(UserInterestTableSeeder::class);
}
}
UserCuisine.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_cuisine');
}
}
UserProfile.php
<?php
namespace App;
class UserProfile
{
public function user()
{
return $this->belongsTo(User::class);
}
public function cuisines()
{
return $this->belongsToMany(UserCuisine::class, 'user_cuisine');
}
}
user_cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('cuisine_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_cuisine');
}
}
cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cuisine');
}
}
Laravel expect the table name to be user_cuisines but you named it user_cuisine without the "s"
You can fix that by changing your migration or adding protected $table = 'user_cuisine'; to your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $table = 'user_cuisine';
}
As naming convention goes, I would recommend changing the table name 👍
Seems user_cuisines table does not exist, You have created cuisine not user_cuisines
Just put below code in UserCuisine model.
protected $table= 'user_cuisine';
I would recommend always use -m flag while creating a model to avoid these types of errors, for example.
php artisan make:model ModelName -m
I was trying to get all the elements sharing a common row data
but I keep getting this error I do not know why
Call to a member function get() on null
Here is the code I used, I have imported the App\User and everything but still not getting it and I have a user in my table with that role_id
My controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use App\Role;
use App\Slaughter;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$farms = User::where('role_id', 3);
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
My user table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->unsignedBigInteger('address_id')->index();
$table->unsignedInteger('role_id');
$table->string('description')->nullable();
$table->timestamps();
$table->foreign('address_id')->references('id')->on('addresses');
});
}
But I am keep getting that error bellow I do not know the why
use App/User;
$farm = User::where('role_id', 3)->get();
Try below code for getting the record
$farm = User::select(['id','name'])->where('role_id', 3)->get();
In case the User class extends Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model{}
calling
$builder = User::where('role_id', 3);
always returns an object of type Illuminate\Database\Eloquent\Builder, therefore, calling
$user= User::where('role_id', 3)->get();
always returns a collection (which might be empty when there is no user with role_id = 3). Check the type of your User class.
I think there are some missed steps that you didn't take.
The User does not refer to the table name but to the model class name. So first things first you need to create a model.
In order to do that you use the command:
php artisan make:model User
If you want a dedicated Models folder(i always use one) you use
php artisan make:model Models/User
By that time you should have a model created but you need to set it up.
Going inside your User.php file you should have something like this:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are NOT mass assignable.
*
* #var array
*/
protected $guarded = [
'created_at', 'updated_at', 'password,
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
//
];
}
Now by including your model at the top of your file you can use your Model class.
This is my migration table
create_profile_table.php:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfileTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profile', function (Blueprint $table) {
$table->integer('userid')->unsigned()->default(0);
$table->string('profilePic')->default('http://b2.com/Images/anup.jpg');
$table->string('about',255);
$table->foreign('userid')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('profile');
}
}
This is my seeder file ProfileSeeder.php:
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Profile;
class ProfileSeeder extends Seeder
{
public function run()
{
Profile::create(array('userid'=>1,'about'=>'Hello World'));
Profile::create(array('userid'=>2,'about'=>'Hello World'));
Profile::create(array('userid'=>3,'about'=>'Hello World'));
Profile::create(array('userid'=>4,'about'=>'Hello World'));
Profile::create(array('userid'=>5,'about'=>'Hello World'));
}
}
This is my model php file Model Profile.php:
namespace App;
class Profile
{
protected $table='profile';
protected $fillable=['userid','about'];
}
shows the error:
[Symfony\Component\Debug\Exception\FatalErrorException] Call to undefined method App\Profile::create()
I am a new laravel5 Learner.
Don't know why this error is showing.
Any kind of help in this issue will be highly appreciated.
Your Profile class needs to extend the Model class if you want to be able to use the eloquent methods, like create(), find() and such.
You should use php artisan to create your models, migrations, seeders and any other Laravel "component", they will work out of the box with minimal effort.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $table='profile';
protected $fillable=['userid','about'];
}