When new user fills out the registration form and hit submit, i can get all of the data that i need using dd($var). But, while inserting to database laravel says Cannot insert the value NULL into column 'password' . Why laravel didn't get my password while inserting to database ?
i have no idea what i did wrong here.
help me ..
this is my RegisterController.php
protected function create(array $data)
{
$pw_hash = Hash::make($data['Password']);
$uuid4 = Uuid::uuid4();
$a = DB::table('Person.Person')->insert(array(
'PersonId' => $uuid4->toString(),
'PersonName' => $data['PersonName'],
'Email' => $data['Email'],
'IsActive' => false,
'IsLoginActive' => false,
'PasswordSalt' => substr($pw_hash, 7, 22),
'PasswordHash' => sha1($pw_inpt.''.$pw_salt),
'IsMale' => $data['IsMale'],
'Email' => $data['Email'],
'Phone' => $data['Phone'],
'LoginName' => $data['Email'],
'PersonName' => $data["NamaDepan"]." ".$data['NamaBelakang'],
'EmailVerifiedAt' => date('Y-m-d'),
'EmailVerified' => false,
'EmailVerificationCode'=> Hash::make(rand(0,100)),
'password'=> 'aaaapass',
));
dd($a);
}
and this is my User.php Model
class User extends Authenticatable{
use Notifiable;
protected $table = 'Person.Person';
// protected $username = 'Email';
public $incrementing = false;
protected $primaryKey = 'PersonId';
const CREATED_AT = 'CreatedDate';
const UPDATED_AT = 'ModifiedDate';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'PersonId',
'Email',
'Phone',
'IsMale',
'password',
'IsActive',
'Position',
'LoginName',
'kencur',
'ClusterId',
'BirthDate',
'BirthPlace',
'PersonName',
'PersonImage',
'PasswordSalt',
'PasswordHash',
'ModifiedDate',
'IsLoginActive',
'EmailVerified',
'WhatsappNumber',
'EmailVerifiedAt',
'EmailVerificationCode',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'PasswordHash',
'PasswordSalt',
'remember_token',
];
public function getEmailForPasswordReset() {
return $this->Email;
}
}
and this is what laravel says:
Cannot insert the value NULL into column 'password', table 'Assess2.Person.Person'; column does not allow nulls. INSERT fails. (SQL: insert into [Person].[Person] ([PersonId], [PersonName], [Email], [IsActive], [IsLoginActive], [PasswordSalt], [PasswordHash], [IsMale], [Phone], [LoginName], [EmailVerifiedAt], [EmailVerified], [EmailVerificationCode], [password]) values (f6377aeb-df36-4f38-aef5-40c7a2240cc5, has sutenan, namadcvbepan#gmail.com, 0, 0, CTDdYYCXHULY4ad8jQJ9WO, $2y$10$CTDdYYCXHULY4ad8jQJ9WOmVqCILEuJPHSgffLlVW5SK7b7Q4qMpy, true, 55, namadcvbepan#gmail.com, 2019-03-04, 0, $2y$10$vcHlXQgukHomPI.FJZe2XOyl0lJd3Lo5rDqVN5SU8gY3UloPLsr.C, aaaapass))
im using laravel 5.7. thank you
PASSWORD is reserved keyword of database. Try to rename that column.
Related
I have this code in my controller:
$createAccreditorAccount = User::firstOrCreate(
['name' => "Accreditor"],
['nonofficial_category_id' => 0],
['role' => "accreditor"],
['email' => "accreditor#cvsucarmona.com"],
['password' => Hash::make('accreditor_cvsucarmona')],
['email_verified_at' => now()]
);
The error I get is this:
SQLSTATE[HY000]: General error: 1364 Field 'role' doesn't have a default value (SQL: insert into `users` (`name`, `nonofficial_category_id`, `updated_at`, `created_at`) values (Accreditor, 0, 2021-05-19 11:36:35, 2021-05-19 11:36:35))
Within the error display, it seems like the columns role, email and password do not fill my record.
I am pretty sure that I have included those columns in my $fillable.
Below is my User model:
<?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 = [
'name',
'role',
'subcategory',
'email',
'password',
'nonofficial_category_id',
];
/**
* 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',
];
public function nonOfficialsCategories()
{
return $this->belongsTo(NonOfficialsCategories::class, 'nonofficial_category_id');
}
}
You don't need to specify each field value in it's own array and provide them as separate parameters, firstOrCreate() only takes 2 parameters, the first array is the unique fields to check against and the second param is the array of values to insert or update. It should be more like this...
$createAccreditorAccount = User::firstOrCreate(
[ 'email' => "accreditor#cvsucarmona.com" ],
[
'name' => "Accreditor",
'nonofficial_category_id' => 0,
'role' => "accreditor",
'email' => "accreditor#cvsucarmona.com",
'password' => Hash::make('accreditor_cvsucarmona'),
'email_verified_at' => now()
]
);
To explain why you are getting the error that you are, the firstOrCreate() method is checking ['name' => "Accreditor"] to see if it's unique and then attempting to insert ['nonofficial_category_id' => 0], which only has the nonofficial_category_id column set, hence the complaint about role not having a default value, ergo, you need to provide a value.
I've been stuck for a little while on a backend issue. PHPStorm tells me that the posts and store method doesn't exist, and I don't know which way to go to solve this problem...
File PostController.php:
public function store(){
$data = request()->validate([
'caption' => ['required', 'string'],
'image' => ['required', 'image']
]);
$imagePath = request('image')->store('uploads','public');
auth()->user()->posts()->create([
'caption' => $data['caption'],
'image' => $imagePath
]);
return redirect()->route('profiles.show', ['user' => auth()->user()]);
}
File User.php:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'username', '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',
];
public function getRouteKeyName()
{
return 'username';
}
public function profile(){
return $this->hasOne('App\Profile');
}
}
Error encountered:
I hadn't created a relationship posts in my User.php.
So I added the relationship this way:
public function posts(){
return $this->hasMany('App\Post');
}
try this :
Post::create([
'caption' => $data['caption'],
'image' => $imagePath
]);
The user has a profile setting. I want if the user changes some fields to be updated. But I have a new column created and should be updated. Maybe someone is not doing it right. Help please. Thank you very much.
Controller
public function profile_settings_post(Request $request){
// Auth Specialist
$user = Auth::user();
// Data Specialist Validate
$data = $request->validate([
'first_name' => 'nullable|string',
'last_name' => 'nullable|string',
'phone_number' => 'nullable|integer',
'gender' => 'nullable',
'date_of_birth' => 'nullable',
'about_me' => 'nullable',
'address' => 'nullable',
'city' => 'nullable|string',
'country' => 'nullable|string',
'postal_code' => 'nullable|integer',
]);
$profile = $user->profile_settings()->updateOrCreate($data);
$profile->save();
// RETURN REDIRECT PROFILE SETTINGS INDEX
return redirect()->route('frontend.specialist.profile.settings');
}
User Model
class User extends Authenticatable
{
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',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static function countPercent($count, $maxCount){
//one percent
$one_percent = $maxCount / 100;
// $count how much is percent
$percent = $count / $one_percent;
return $percent;
}
// 1 User have 1 profile settings (ONE TO ONE)
public function profile_settings(){
return $this->hasOne(Profile_Settings::class);
}
}
Profile_Settings Model:
class Profile_Settings extends Model
{
// Fill in db
protected $fillable = [
'first_name', 'last_name', 'phone_number',
'gender', 'date_of_birth', 'about_me',
'address', 'city', 'country', 'postal_code',
];
// Profile settigns model belongs to User
public function user(){
return $this->belongsTo(User::class);
}
}
When I edit some kind of field. A new field is created in the database
profile settings database not working update create new columns
You probably didn't read carefully how works updateOrCreate
It performs update based on the condition that you're passing in and updates the fields, that you want, so you will have to pass 2 arrays.
Example from Laravel's webitse
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
So this means we are updating all rows, where 'departure' = 'Oakland', 'destination' = 'San Diego' and setting price to 99$.
I your case you should decide the condition, when you should perform update query, it will be 1st array, and also decide which fields should be updated, put it in 2nd array.
I am trying to make the 'name' and 'email' properties guarded in my user model, because I don't want my users to be able to change them after registration.
My user model looks like this:
protected $fillable = [
'province',
'city',
'street',
'postal',
'cellphone',
'facebook',
'instagram',
];
protected $guarded = [
'name',
'email',
'password',
'account_type',
'verified_type',
];
Upon registration, Laravel by default mass assigns these values like so:
//Create the user
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'province' => $data['province'],
'city' => $data['city'],
'street' => $data['street'],
'postal' => $data['postal'],
'cellphone' => $data['cellphone'],
'trial_ends_at' => \Carbon\Carbon::now()->addMonths(3),
'account_type' => $accountType,
]);
But this throws an error for me because 'name' doesn't have a default value and isn't nullable. I understand why I'm getting the error and how to fix it, but I would like to know how I should go about assigning the name and email if they don't have default/nullable properties. For example, something like:
$user = new User();
$user->name = $request->name;
$user->email = $request->email;
$user->save();
$user->update([
//the rest of the mass assignable values
]);
Or is there an easier way?
You can accomplish by adding this to your model.
/*
Attribute which are protected from updating.
*/
protected $protected = [
'name', 'email'
];
protected static function boot()
{
parent::boot();
static::saving(function ($model) {
if($model->id){
foreach($model->protected as $attribute){
$model->$attribute = $model->getOriginal($attribute);
}
}
});
}
Hope the code is self-expresive.
you can use a mutator and remove name from guarded attributes. read the docs here
public function setNameAttribute($newName)
{
if(isset($this->name) && $this->name !== null){
throw new \Exception;
//or do nothing
} else {
$this->attributes['name'] = $newName;
}
}
and do the same for email too
I am pretty much new to laravel(5.2), here i want to concatenate two values say first name and last name during user registration and save it to database, honestly as am new to this whole concept i have very little idea of doing it...it would be great if i could get some help....
User.php
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
AuthController.php
class AuthController extends Controller
{
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|max:255',
'last_name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}
if you want to save the new value to data base you must register it in you fillable, also to alter the database to accept the new column
protected $fillable = [
'user_name', 'first_name', 'last_name', 'email'
];
protected function create(array $data)
{
return User::create([
'user_name' => $data['first_name'].' '.$data['last_name'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
you may want to remove first_name and last_name.. and store only full name, or you can ignore storing the full name, and in User.php model you can override the toArray() method and make it returns the full name which you can concatenate just like above
Concatenation of two strings in a php concept, it do not relates to laravel in any way. You can easily concatenate two or more string like:
$str = $data['first_name'].' '.$data['last_name']; // concatenate by using space
But this does not help you because you are inserting user data into user table which have first_name, last_name columns. So you have to insert them individually.
// to concat with a space in between use
$str = $data['first_name'].' '.$data['last_name'];
// to concat to one big string without spacing use
$str = $data['first_name'].$data['last_name'];