SQLSTATE[42P01]: Undefined table when try to create new user - php

i'm new in laravel php and i try to create a new user with api post request and when i send this request i have a porblem when i do it
I use psgql and laravel 9. i use that
link to do this and custom somthing
This is my code:
i has User model like
class User extends Authenticatable
{
use HasApiTokens,HasFactory, Notifiable;
public $timestamps = false;
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'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',
];
}
and here is my AuthController to create new user
class AuthController extends Controller
{
/**
* Create User
* #param Request $request
* #return User|\Illuminate\Http\JsonResponse
*/
public function createUser(Request $request){
try{
$validateUser = Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email|unique:users,email',
'password'=>'required'
]);
if($validateUser->fails()){
return response()->json([
'status'=>false,
'message'=>'validation error',
'errors'=>$validateUser->errors()
],401);
}
$user = User::create([
'first_name'=>$request->first_name,
'last_name'=>$request->last_name,
'email'=>$request->email,
'password'=> Hash::make($request->password)
]);
return response()->json([
'status'=>true,
'message'=>'User created successfully',
'token'=>$user->createToken("API TOKEN")->plainTextToken
],200);
}
catch (\Throwable $th){
return response()->json([
'status'=>false,
'message'=>$th->getMessage()
],500);
}
}
}
and i got problem when i send post request json
like
{
"status": false,
"message": "SQLSTATE[42P01]: Undefined table: 7 ERROR: relation \"users\" does not exist\nLINE 1: select count(*) as aggregate from \"users\" where \"email\" = $1\n ^ (SQL: select count(*) as aggregate from \"users\" where \"email\" = something#abc.com)"
}
please help me

Instead of:❌
'email'=>'required|email|unique:users,email',
Use this:✅
'email'=>'required|email|unique:user,email',
Note the table name defined in your User Model is user.
Hence, that has to be reflected in your validation rules as well.

You forget to check you table in in validation
'email'=>'required|email|unique:users,email',
replace users to user

You are using the wrong table name in the validation, you need to replace 'users' by 'user' :
'email'=>'required|email|unique:users,email' to be 'email'=>'required|email|unique:user,email'

Related

How to save entities across two databases in Laravel (Backpack)

I am new with Laravel and of course also with backpack.
I am using laravel 7.x and backpack 4.1 with both MySql and MongoDb.
The situation I am facing is that I have a company model with some attributes which are in MySql (both save and update working great with for the attributes stored in MySql) and other attributes that should be stored in MongoDb.
I have a CompanyPropertyCollection model for the attributes which I want to be stored in MongoDb
All these company will have a variable number of other arbitrary properties, which I want to save in mongo.
These properties may be simple scalar values or more complex values too (think arrays of objects), hence the idea to save them in mongo.
MySql Company table:
My question is the following:
What is the best practice to save attributes of an entity in two distinct databases from BackPack? I override the CreateOperation, UpdateOperation with the store() and update() functions something like this:
Company model:
class Company extends Model
{
use \Backpack\CRUD\app\Models\Traits\CrudTrait;
use SoftDeletes;
use HybridRelations;
protected $connection = 'mysql';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'company_type',
'is_active',
'package_id',
'certification_id',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'is_active' => 'boolean',
'package_id' => 'integer',
'certification_id' => 'integer',
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users()
{
return $this->belongsToMany(\App\Models\User::class);
}
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function package()
{
return $this->belongsTo(\App\Models\Package::class);
}
public function certification()
{
return $this->hasMany(\App\Models\Certification::class);
}
public function properties()
{
return $this->hasOne(\App\Models\CompanyPropertyCollection::class);
}
}
CompanyPropertyCollection model:
class CompanyPropertyCollection extends Model
{
use SoftDeletes;
protected $connection = 'mongodb';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
//'company_id',
'email',
'big_news_id',
'phone.number',
'phone.country_prefix',
'phone.area_prefix',
'phone.postfix',
'year_of_foundation',
'nr_of_employees',
'nr_of_branches',
'company_size',
'subtitle',
'homepage',
'country_code',
'city',
'street',
'post_code',
'uid_nr',
'registration_nr',
'total_sales_area',
'total_annual_bisuness_volume',
'short_portrait',
'long_portrait',
'embedded_video',
'certificates',
'gallery',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'gallery' => 'array',
];
public function company()
{
return $this->belongsTo(\App\Models\Company::class);
}
}
CompanyCrudController :
public function update()
{
//$this->update( $company->properties);
$response = $this->traitUpdate();
// do something after save
//use registered observer
return $response;
}
Currently I am trying to use a CompanyObserver and on saving to store the data for mongo from the Request.
class CompanyObserver {
public function saving(Company $company)
{
//dd(request()->request);
$request = request()->request;
dd($company->properties());
//save to MongoDb
dd('saving methond on the observer');
}
}
If you need to perform some action after saving a model, like saving some user data in another db with a different type. You can override the model's save method.
Inside your model, add a method like the below
public function save(array $options = array())
{
if (parent::save($options)) {
// Model has been saved in mysql, now save in mongoDB
}
}

Laravel: Why Laravel accessor not work getIsVerifiedAttribute()?

I need to check the email of my users. So I add a new attribute to my User model named "is_verified" that returns me a boolean to know if the user has checked the email or not.
I running on PHP 7.2.5 with PHPUnit 7.5.15 and Laravel 5.8
model: User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Str;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password', 'token', 'email_verified_at'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Retrive if user as vierfied
*
* #return boolean
*/
public function getIsVerifiedAttribute()
{
// dump(!is_null($this->email_verfied_at));
return !is_null($this->email_verfied_at);
}
/**
* Set if user is verified
*
* #param boolean $status
* #return void
*/
public function setIsVerifiedAttribute(bool $value)
{
if ($value) {
$this->attributes['token'] = null;
$this->attributes['email_verified_at'] = now();
} else {
$this->attributes['token'] = self::generateToken();
$this->attributes['email_verified_at'] = null;
}
}
/**
* Generate token to verify email
*
* #param integer $length
* #return string
*/
public static function generateToken(int $length = 64): string
{
$token = Str::random($length);
if (self::where('token', $token)->exists())
{
return self::generateToken($length);
}
return $token;
}
}
My unit test:
/** #test */
public function check_if_user_as_validate_email()
{
$user = factory(User::class)->create();
$this->assertFalse($user->is_verified);
$user->is_verified = true;
$user->save();
$this->assertTrue($user->is_verified);
$user->is_verified = false;
$user->save();
$this->assertFalse($user->is_verified);
}
The functions do not return me the good value every time
The reason your test isn't working is because you have a typo in your getIsVerifiedAttribute accessor. email_verfied_at should be email_verified_at.
public function getIsVerifiedAttribute()
{
return !is_null($this->email_verified_at);
}
Out-of-the-box, the User factory sets the email_verified_at field for you so I would suggest you change the code in your test for creating a User to:
$user = factory(User::class)->create([
'email_verified_at' => null
]);
This next bit is just an FYI but there are already methods included in with Laravel to check if a User is verified or not and to set the email_verified_at value:
$user->hasVerifiedEmail();
and
$user->markEmailAsVerified();

return specific Data using has Role

My Code Here is Working Fine but although he is returning user Role in the return can i prevent user roles from returning it's belongs to relation using role_id in users Table
$paths = Path::with(['user','tags'])->where('category_id',1)->get();
foreach($paths as $path){
if($path->user->hasRole('admin')){
$AdminPaths [] = $path;
}
if($path->user->hasRole('user')){
$UserPaths [] = $path;
}
}
return $UserPaths;
My User Model
class User extends \TCG\Voyager\Models\User
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password', 'username'
];
/**
* 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',
];
}
You are calling the function hasRole from here:
https://github.com/the-control-group/voyager/blob/1.2/src/Traits/VoyagerUser.php
It executes loadRolesRelations() that loads the roles relationships and thats why users come with the role relation loaded.
You could just unset the role relation after checking the role like:
foreach($paths as $path){
if($path->user->hasRole('admin')){
$AdminPaths [] = $path;
}
if($path->user->hasRole('user')){
$UserPaths [] = $path;
}
unset($path->user->role);
}

Call to a member function addvoter() on null

On Laravel 5.4.1 I'm always getting this error when using ajax
FatalThrowableError in avController.php line 53: Call to a member function addvoter() on null
but it seems to work perfectly without ajax. I think the problem starts from $request->user()->addvoter()->save($voter); which is my line 53 but I don't understand it;
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
if ($request->isMethod('post')){
$voter = new voter();
$voter->FirstName = $request->fname;
$voter->LastName= $request->lname;
$voter->Email = $request->email;
$voter->PhoneNumber = $request->phone;
$voter->Gender = $request->optradio;
$voter->StudentID = $request->sID;
$voter->Level = $request->level;
$voter->Course = $request->course;
$voter->Stream = $request->stream;
$voter->Nationality = $request->nat;
$voter->ProfileImg = $request->image;
$request->user()->addvoter()->save($voter);
$response = array(
'fname' => $request->fname,
'lname' => $request->lname,
'msg' => 'Setting created successfully',
);
return response()->json($response);
}
return response()->json(['response' => 'This is get method']);
}
my user model
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function addcandidate(){
return $this->hasMany('elpebi\addcandidate');
}
public function addstcandidate(){
return $this->hasMany('elpebi\stcandidate');
}
public function addvoter(){
return $this->hasMany('elpebi\voter');
}
public function newelection(){
return $this->hasMany('elpebi\election');
}
my voter model
protected $fillable = ['FirstName', 'LastName', 'Email',
'Gender', 'StudentID', 'Level', 'Course',
'Stream', 'Nationality', 'ProfileImg' ];
public function user(){
return $this->belongsTo('elpebi\User');
}
If your user is logged in, I think you can do this:
auth()->user()->addvoter()->save($voter);

Validator not using specified rules, passes when should fail, using way/database

I'm using the way/database package for validation with Laravel 4.2 and have set up a simple user registration method.
I'm testing this by trying to create a new user with an email address that is already present. The validator returns true, and then goes onto give the error:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'test2#test.com' for key 'users_email_unique' (SQL: insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (test2#test.com, 123, 2015-01-29 11:50:37, 2015-01-29 11:50:37))
So is this something wrong with my model?
The controller:
public function store()
{
$user = User::create(Input::only('email', 'password'));
if ($user->hasErrors()){
return Response::json(array(
'error' => $user->getErrors()
));
}
Auth::login($user);
return Response::json(array('success' => 'true'));
}
The User.php model:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Model implements UserInterface, RemindableInterface {
use UserTrait, RemindableTrait;
protected $fillable = array(
'email', 'password'
);
protected static $rules = [
'email' => 'required:unique'
];
//Use this for custom messages
protected static $messages = [
'email.required' => 'An email address is required'
];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
}
Here's the validation model from way/database:
class Model extends Eloquent {
/**
* Error message bag
*
* #var Illuminate\Support\MessageBag
*/
protected $errors;
/**
* Validation rules
*
* #var Array
*/
protected static $rules = array();
/**
* Custom messages
*
* #var Array
*/
protected static $messages = array();
/**
* Validator instance
*
* #var Illuminate\Validation\Validators
*/
protected $validator;
public function __construct(array $attributes = array(), Validator $validator = null)
{
parent::__construct($attributes);
$this->validator = $validator ?: \App::make('validator');
}
/**
* Listen for save event
*/
protected static function boot()
{
parent::boot();
static::saving(function($model)
{
return $model->validate();
});
}
/**
* Validates current attributes against rules
*/
public function validate()
{
$v = $this->validator->make($this->attributes, static::$rules, static::$messages);
if ($v->passes())
{
return true;
}
$this->setErrors($v->messages());
return false;
}
/**
* Set error message bag
*
* #var Illuminate\Support\MessageBag
*/
protected function setErrors($errors)
{
$this->errors = $errors;
}
/**
* Retrieve error message bag
*/
public function getErrors()
{
return $this->errors;
}
/**
* Inverse of wasSaved
*/
public function hasErrors()
{
return ! empty($this->errors);
}
}
Can anyone point me towards what I'm doing wrong?
Try changing
protected static $rules = [
'email' => 'required:unique'
];
to
protected static $rules = [
'email' => 'required|unique'
];
The Laravel docs will help
http://laravel.com/docs/4.2/validation

Categories