Laravel not working method updateOrCreate - php

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.

Related

Laravel 8 firstOrCreate Not Working With $fillable

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.

Method store & posts not found [LARAVEL]

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
]);

some data cannot be inserted into database

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.

How shall i concatenate two or more values/variables to a new variable in laravel

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'];

Laravel/Ardent: SQLSTATE[HY093]: Invalid parameter number: mixed named and positional parameters

I'm trying to validate a User using Ardent's validate() method, but I always receive the HY093 error with the following extra information
(SQL: select count(*) as aggregate from:userswhereemail= my.email#gmail.com)
I used Sentry2 for my 'users' table database migration.
I have my User model set up like this:
/**
* Validation Rules for ARDENT here
*/
public static $rules = [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique::users',
'password' => 'required|between:8,32|confirmed',
'password_confirmation' => 'required|between:8,32',
];
/**
* The attributes that can be added to a new User using $user->fill()
*
* #var array
*/
protected $fillable = [
'first_name',
'last_name',
'email',
'password',
'password_confirmation'
];
/**
* Automatically removes _confirmation attributes
*
* #var boolean
*/
public $autoPurgeRedundantAttributes = true;
From a form, I have POST data that includes ['email', 'first_name', 'last_name', 'password', 'password_confirmation] with their respective values that go to the following function in my UserController:
public function signup() {
// Create a new User object
$user = new User();
// Populate attributes with information described in User->fillable
$user->fill( Input::all() );
// Check if info is valid using Ardent's validate() method
if ( $user->validate() ) {
....
....
....
My code always fails on the if ( $user->validate() ) line. Can anyone help me shed some light upon this situation?
The issue was this line
'email' => 'required|email|unique::users'
Should have been
'email' => 'required|email|unique:users'
According to The Laravel Docs

Categories