Laravel column missing during seeding - laravel-9

I'm encountering error during db seeding
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'code ' in 'field list' (SQL: insert into medicines (price, quantity, code , updated_at, created_at) values (3831, 23, 12345DFG, 2022-07-30 15:04:29, 2022-07-30 15:04:29))
medicine migration
public function up()
{
Schema::create('medicines', function (Blueprint $table) {
$table->id();
$table->string("price");
$table->string("quantity");
$table->string("code");
$table->timestamps();
$table->softDeletes();
});
}
model medicine.php
class medicine extends Model
{
use HasFactory,softDeletes;
protected $fillable=[
'price',
'quantity',
'code',
];
}
This is the way factory looks like;
public function definition()
{
return [
'name' => $this->faker->name,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return \Illuminate\Database\Eloquent\Factories\Factory
*/
public function unverified()
{
return $this->state(function (array $attributes) {
return [
'email_verified_at' => null,
];
});
}
}
I use
php artisan db:seed to seed through terminal

Related

Object of class Faker\UniqueGenerator could not be converted to string

I am using laravel 9. I am trying to generate some fake users to boost my db using factoreis and seeders.
When i try to seed my db i get this error
Object of class Faker\UniqueGenerator could not be converted to string
at D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
661▕ $value,
662▕ match (true) {
663▕ is_int($value) => PDO::PARAM_INT,
664▕ is_resource($value) => PDO::PARAM_LOB,
➜ 665▕ default => PDO::PARAM_STR
666▕ },
667▕ );
668▕ }
669▕ }
1 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:665
PDOStatement::bindValue(Object(Faker\UniqueGenerator))
2 D:\PROJECTS\LARAVEL\todo-list\vendor\laravel\framework\src\Illuminate\Database\Connection.php:540
Illuminate\Database\Connection::bindValues(Object(PDOStatement))
this my UserFactory
class UserFactory extends Factory
{
/**
* Define the model's default state.
*
* #return array<string, mixed>
*/
public function definition()
{
return [
'name' => fake()->name(),
'username' => fake()->unique(),
'company' => fake()->sentence(),
'position' => fake()->sentence(),
'bio' => fake()->realText($maxNbChars = 100),
'picture' => fake()->imageUrl(90, 90),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => Hash::make('password'), // password
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*
* #return static
*/
public function unverified()
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
After looking arround for a while I found that fake()->unique() does not return a string. So I tried to convert it to string but It also gives me a error saying Unknown format "toString" in Faker\Generator.php:731
[Problem solved]
I just had to edit my UserFactory username to this
'username' => fake()->unique()->text(16),

error in Laravel8: SQLSTATE[42S02]: Base table or view not found: 1146 Table

I have started a new project with Laravel 8.
I use the starter kit Laravel Breeze.
But I can't customize fields.
I have changed fields in the migration and Register Controller and User model.
here is my code:
migration file.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class TblUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tbl_users', function (Blueprint $table) {
$table->id();
$table->string('fullname');
$table->string('username');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('phone');
$table->string('organization_type');
$table->string('community_dev_auth_id');
$table->string('file_names');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tbl_users');
}
}
register controller file.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Providers\RouteServiceProvider;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*
* #return \Illuminate\View\View
*/
public function create()
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*
* #throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request)
{
$request->validate([
'fullname' => 'required|string|max:255',
'username' => 'required|string|max:255',
'email' => 'required|senter code heretring|email|max:255|unique:users',
'phone' => 'required|string|max:255',
'organization' => 'required|string|max:255',
'community' => 'required|string|max:255',
// 'phone' => 'required|string|max:255',
'password' => 'required|string|min:8',
]);
Auth::login($user = User::create([
'fullname' => $request->fullname,
'username' => $request->username,
'email' => $request->email,
'phone' => $request->phone,
'organization_type' => $request->organization,
'community_dev_auth_id' => $request->community,
'password' => Hash::make($request->password),
]));
event(new Registered($user));
return redirect(RouteServiceProvider::HOME);
}
}
user model file.
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fullname',
'username',
'email',
'phone',
'organization',
'community',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
I have run this project, but it returns this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'ambulance_dubai.users' doesn't exist (SQL: select count(*) as
aggregate from users where email = asdf#sdf.df)
Since you are using a different table name for the user model you have to define it in your model. By default, Laravel will look for the plural name
of a model(users) if your model doesn't have a table property.
Add this to the user model:
protected $table='tbl_user';
first, you will check user table was migrate, the user table not to be migrated
use this command
php artisan migrate
Open your User Model
and add $table
class User extends Authenticatable {
protected $table = 'users';
}
Another cause could be that the validation has a different name for the table. For example, having the table tbl_users in the validation could exist an error and have:
'required|unique:tbl_user,email'.
The letter "s" is missing and the error would be thrown.
`
return [
//
'name' => 'required',
'image' => 'required',
'email' => 'required|unique:users,email',
'username' => 'required|unique:users,username',
'password' => 'required|min:8',
];
`
Where you see users should correspond to your table name in the database.
This is under validation.

General error: 1364 Field 'title' doesn't have a default value

I have very weird problem while trying to create new item. Code and error below.
Mugration:
Schema::create('inventory_departments', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->integer('parent_id')->unsigned()->default('1');
//$table->timestamps();
$table->foreign('parent_id')->references('id')->on('inventory_departments');
});
Model:
protected $fillable = [
'title',
'parent_id',
];
Controller:
$data = [
'title' => 'test',
'parent_id' => '3',
];
$result = InventoryDepartment::create($data);
And i receive such error:
SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into `inventory_departments` () values ())
Should you not be passing in $data to create?
$result = InventoryDepartment::create($data);

Error "Call to undefined method Illuminate\Auth\GenericUser" when accessing to hasMany relationship of Auth::user()

I defined a relationship One-to-Many between User and Patient, but when I try to save a new patient record with the authenticated user I get the error
Call to undefined method Illuminate\Auth\GenericUser::patients()
Here are my tables:
// Users table
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
$table->softDeletes();
});
// Patients table
Schema::create('patients', function (Blueprint $table) {
$table->increments('id');
//Foreign key
$table->integer('user_id')->unsigned();
$table->string('ci')->unique();
$table->string('name');
$table->string('last_name');
$table->string('gender');
$table->date('birth_date')->nullable();
$table->string('place')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('user_id')
->references('id')->on('users');
});
In PatientController I call Auth::user() to save a new patient:
public function store(PatientRequest $request){
$patient = new Patient($request->all());
Auth::user()->patients()->save($patient);
$last = Patient::get()->last();
return redirect()->route('patient.histories.create', [$last->id])->with('message', 'Success!');
}
And the relationships are defined as follows:
// IN USER MODEL
public function patients(){
return $this->hasMany('App\Patient');
}
// IN PATIENT MODEL
public function user(){
return $this->belongsTo('App\User');
}
At this point I really don't know what is wrong, but when I create a new patient record from tinker it works as expected:
>>> $patient = new App\Patient;
>>> $patient->ci = "1234567";
.......
.......
>>> $user = App\User::first();
>>> $user->patients()->save($patient);
Can someone spot where is the error, please?
I found out what was the problem, I left uncommented both options in the providers array inside the auth.php file:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// ERROR
// Call to undefined method Illuminate\Auth\GenericUser::patients()
// 'users' => [
//'driver' => 'database',
//'table' => 'users',
// ],
],

Can't authenticate with different table

I've changed the auth.php file in order to authenticate my users according to authors table. But I keep getting No account for you when I'm running test route.
auth.php
<?php
return array(
'driver' => 'eloquent',
'model' => 'Author',
'table' => 'authors',
'reminder' => array(
'email' => 'emails.auth.reminder', 'table' => 'password_reminders',
),
);
routes.php
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => Hash::make('giannis'));
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
AuthorsTableSeeder.php
<?php
class AuthorsTableSeeder extends Seeder {
public function run()
{
// Uncomment the below to wipe the table clean before populating
DB::table('authors')->delete();
$authors = array(
[
'username' => 'giannis',
'password' => Hash::make('giannis'),
'name' => 'giannis',
'lastname' => 'christofakis'],
[
'username' => 'antonis',
'password' => Hash::make('antonis'),
'name' => 'antonis',
'lastname' => 'antonopoulos']
);
// Uncomment the below to run the seeder
DB::table('authors')->insert($authors);
}
}
Addendum
I saw in another post that you have to implement the UserInterface RemindableInterface interfaces. But the result was the same.
Author.php
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $guarded = array();
public static $rules = array();
public function posts() {
return $this->hasMany('Post');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return "giannis#hotmail.com";
}
}
You don't need to Hash your password when you are using Auth::attempt(); so remove Hash::make from routes
Route::get('test', function() {
$credentials = array('username' => 'giannis',
'password' => 'giannis');
if (Auth::attempt($credentials)) {
return "You are a user.";
}
return "No account for you";
});
and it will work like a charm!