When register at Laravel using eloquent, my PK field at table users is userid [auto increment] I want to insert the current id at the same time when I run the User::create(); to different field (create_by [int]) so the create_by field will be filled with the same value as the primary key field userid, like this code:
User::Create([
'user_email' => $data['user_email'],
'user_password' => bcrypt($data['user_password']),
'first_name' => 'John',
'last_name' => 'Doe',
'department_id' => 1,
'user_level' => 1,
'create_date' => Carbon::now('Asia/Jakarta'),
'create_by' => // value same as userid the PK
])
How to get the current id to be used in different field?
I actually try some trick to get the id like this:
User::insertGetId([
'user_email' => $data['user_email'],
'user_password' => bcrypt($data['user_password']),
'first_name' => 'John',
'last_name' => 'Doe',
'department_id' => 1,
'user_level' => 1,
'create_date' => Carbon::now('Asia/Jakarta')
])
It was good to return the inserted id, but my expectation is I want to save the current id to the create_by field at the same time user_id was inserted, not after the data was saved.
You can try
$user = User::create([...]);
$user->create_by = $user->id;
$user->update();
Update
You can get the last user in the database. But be aware this is not 100% safe.
$lastUser = User::orderBy('id', 'desc')->first();
$user = User::create([
...
'create_by' => $lastUser->id + 1
]);
Might be its not a good way but it will work fine Try it
I am assuming db fields please review query as desired. Its a hint to work
1st need to get max id of user as
$users = User::whereRaw('id = (select max(`userid`) from users)')->first();
$create_by= $users->id+1;
//dd($create_by);
//die;
If you remove commented code it will give you next id now pass this variable as
'create_by' => $create_by,
You can do it by:
$user_save_obj = User::Create([
'user_email' => $data['user_email'],
'user_password' => bcrypt($data['user_password']),
'first_name' => 'John',
'last_name' => 'Doe',
'department_id' => 1,
'user_level' => 1,
'create_date' => Carbon::now('Asia/Jakarta')
])
$last_inserted_id = $user_save_obj->id;
$user_update_obj = User::find($last_inserted_id);
$user_update_obj->created_by = $last_inserted_id;
$user_update_obj->save();
Related
$responsible_users = collect($request->responsible_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::RESPONSIBLE_ROLE]));
$subordinate_users = collect($request->subordinate_users)->map(fn ($user_id) => new OrganizationElementUser(['user_id' => $user_id, 'organization_element_id' => $organization_element_id, 'type' => DeviceAuthAndHierarchyElementRole::DIRECT_SUBORDINATE_ROLE]));
$internal_users = $responsible_users->merge($subordinate_users)->toArray();
OrganizationElementUser::upsert($internal_users, ['user_id', 'organization_element_id', 'type'], ['user_id', 'organization_element_id', 'type']);
Why is my upsert creating duplicate records?
My user_id, organization_element_id, type fields can individually be duplicate but all 3 of them combined creates a unique record
ex. of what I want is:
user_id == 1 && organization_element_id == 2 && type == 'test'
//ignore if true otherwise insert
You can use UpdateOrCreate method. Documentation here.
User::updateOrCreate([
'user_id' => $user_id,
'organization_element_id' => 2,
'type' => 'test'], //if everything matches with these conditions, the row will get updated, otherwise, it will be inserted. It is like the where clause.
['column_xyz' => $request->new_string],
);
I'm trying to use the registerController to insert data into 2 tables of SQL, the Users table of Laravel and one table called personas that is associated to the Persona Model.
$datos= ['nombre' => $data['name'],'apellido' => $data['surname'],'cedula' => $data['cedula'],'email' => $datos['email'],
'telefono' =>$datos['telefono'],'direccion' =>$datos['direccion'],'ciudadResi' =>$datos['ciudadResi'],'genero' =>$datos['genero'],];
Persona::create($datos)([
'nombre' => $datos['nombre'],
'apellido' => $datos['apellido'],
'cedula' => $datos['cedula'],
'email' => $datos['email'],
'telefono' =>$datos['telefono'],
'direccion' =>$datos['direccion'],
'ciudadResi' =>$datos['ciudadResi'],
'fechaNacimiento' =>'1998-03-05',
'genero' =>$datos['genero'],
'estado'=> '1',
'idTipoPersona'=>'2'
]);
User::create($data)([
'name' => 'clienteUser',
'surname' => $data['surname'],
'email' => $data['email'],
'nick' => $data['nick'],
'password' => Hash::make($data['password']),
'role' => 'cliente'
]);
That is the code in the RegisterController that is generated by auth of Laravel, what I'm trying to do is get the $data from the form in register.blade because I don't need the updated_at and created_at that $data have I want to store the values I want to insert in the persona table in the $datos array, insert them into the table and insert the values I need for User form Data.
When I try to do that it says that $datos is undefined. What should I need to solve the problem? English is not my main language so I would appreciate if explanations are easy.
inside $datos array, there is $datos present.. i think thats where the error comes from.. i think it should be $data instead of $datos inside $datos array
I got this code in laravel that allows an administrator to update an user's password:
public function editarmembro(Request $dados) {
$validatedData = $dados->validate([
'name' => 'required',
'email' => 'required',
'credencial' => 'required',
]);
$dados = $dados->all();
if (!empty($dados['password'])) {
$dados['password'] = Hash::make($dados['password']);
}
DB::table('users')->where('id', $dados['id'])->update(
[ 'name' => $dados['name'], 'email' => $dados['email'], 'credencial' => $dados['credencial'], 'password' => $dados['password'], 'sobre' => $dados['sobre'], 'updated_at' => Carbon::now(), ]
);
return redirect()->route('membros')->with('mensagemSucesso', 'As informações do membro "'.$dados['name'].'" foram atualizadas com sucesso.');
}
My problem is, if he left the password field blank, i get an error screen saying that the password field cannot be NULL. I want my code to NOT update the password if he left the password field blank, but DO update if he inserts something in password field.
Help, pls.
You can remove it from the $dados array if it's empty:
if (!empty($dados['password']))
$dados['password'] = Hash::make($dados['password']);
else
unset($dados['password']);
or with ternary operator
!empty($dados['password'])? $dados['password'] = Hash::make($dados['password']): unset($dados['password']);
and since all the names of the fields match those of the request and the updated_at field should auto-complete, you don't need to reassemble the array for the update.
DB::table('users')->where('id', $dados['id'])->update($dados);
If you want to reassemble the array anyway, you can do so
$update_dados = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
if (!empty($dados['password']))
$update_dados['password'] = Hash::make($dados['password']);
DB::table('users')->where('id', $dados['id'])->update($update_dados);
You just need to merge to the array with all the values (except the password) the password only if exists / is set:
$your_array = [
'name' => $dados['name'],
'email' => $dados['email'],
'credencial' => $dados['credencial'],
'sobre' => $dados['sobre'],
'updated_at' => Carbon::now(),
];
DB::table('users')->where('id', $dados['id'])->update(
empty($dados['password']) ? $your_array : array_merge($your_array, ['password' => $dados['password']])
);
Here I used updateOrCreate method to post data but when I use this method old data replaced by new data but I want to add new data without updating or replacing exists data.
here is the code for insert data
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
I solved myself, I stored old data into $extSeat then merge with new data, I don't know the logic is correct or wrong but works
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],// row to test if schedule id matches existing schedule id
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);
What is the optimum way of generating gender using faker, having generated a name so that the gender matches the name
return [
'name' => $faker->name,
'email' => $faker->safeEmail,
'username' => $faker->userName,
'phone' => $faker->phoneNumber,
'gender' => $faker->randomElement(['male', 'female']),//the gender does not match the name as it is.
'address' => $faker->address,
'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
'password' => bcrypt('secret')
];
Looking at the documentation and an issue raised on the their Github issues section, your solution seems to be the best. Some methods allow you to specify the gender for a name so you could do like this:
$gender = $faker->randomElement(['male', 'female']);
return [
'name' => $faker->name($gender),
'email' => $faker->safeEmail,
'username' => $faker->userName,
'phone' => $faker->phoneNumber,
'gender' => $gender,
'address' => $faker->address,
'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
'password' => bcrypt('secret')
];
Hopefully this fits your requirement.
to do it without additional variable, do it like this
return [
'gender' => $faker->randomElements(['male', 'female']),
'name' => $faker->name(function (array $user) {return $user['gender'];})
]
hope it helps
The method randomElements is gonna return an array with one single element, so if you want to get 'female' or 'male', don't forget to add at the end of the first line this: [0]. You need the first element (index 0) of the resulting array (that only has one element).
$gender = $faker->randomElements(['male', 'female'])[0];
One more thing. In order to obtain exactly what you want, you need to use firstName instead of name. This way the first name will be according to the gender. Do it this way:
return [
'name' => $faker->firstName($gender),
'email' => $faker->safeEmail,
'username' => $faker->userName,
'phone' => $faker->phoneNumber,
'gender' => $gender,
'address' => $faker->address,
'dob' => $faker->date($format = 'Y-m-d', $max = 'now'),
'password' => bcrypt('secret')
];
One last thing: If you use 'Male' and 'Female', instead of 'male' and 'female', this is NOT gonna work!!
Actually all answers did not really work for me. It returned female or male only.
I had almost the same issue. I needed a random element out of three genders 👍😀. It always gave me this error message:
Illuminate\Database\QueryException : Array to string conversion (SQL: insert
into `users` (`name`, `gender`, `email`, `admin`, `author`, `password`,
`remember_token`) values (Margaret Robel I, male, azieme#example.com, 1, 0,
dummylogin, gwKdVN7zYv))
at /Users/mangrove/Desktop/php-workspace/laravel-
mangrove/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll
format the error
661| // message to include the bindings with SQL, which will make this
exception a
662| // lot more helpful to the developer instead of just the
database's errors.
663| catch (Exception $e) {
> 664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 ErrorException::("Array to string conversion")
/Users/mangrove/Desktop/php-workspace/laravel-
mangrove/vendor/laravel/framework/src/Illuminate/Database/
MySqlConnection.php:80
2 PDOStatement::bindValue()
/Users/mangrove/Desktop/php-workspace/laravel-
mangrove/vendor/laravel/framework/src/Illuminate/
Database/MySqlConnection.php:80
After a look at the documentation for Faker v.1.8.0
This worked for me:
public function run()
{
$faker = Faker::create();
foreach(range(1,10) as $index){
// Returns always random genders according to the name, inclusive mixed !!
$gender = $faker->randomElement($array = array('male','female','mixed'));
DB::table('users')->insert([
'name' => $faker->name($gender),
'gender' => $gender,
'email' => $faker->unique()->safeEmail,
'admin' => $faker->numberBetween($min = 0, $max = 1),
'author'=> $faker->numberBetween($min = 0, $max = 1),
'password' => 'dummylogin',
'remember_token' => str_random(10),
]);
}
}
It turns out mixed genders will always have different names, because you can
be either way 😄⚧