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 😄⚧
Related
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']])
);
I have a model I plan to save the input to two different tables but I have an error
Symfony\Component\Debug\Exception\FatalThrowableError Argument 1
passed to Illuminate\Database\Eloquent\Builder::create() must be of
the type array, object given, called in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Support\Traits\ForwardsCalls.php
on line 23
the first table is Transaction_in and the second is Transaction_in_detail. I planned to use idTransaction_in as a connector between 2 tables and that column is not a primaryKey (is it a good practice)? I can save the input to Transcation_in table but still failed to save the input to the 2nd table and I don't know how to make the idTransaction_in column as a connector.
public function store(Request $request)
{
$request->validate([
'supplier_name' => 'required',
'transaction_in_date' => 'required|before_or_equal:today',
'device_type_name' => 'required',
'device_brand_name' => 'required',
'device_spec' => 'required|max:255',
'price' => 'required',
'amount' => 'required',
'total_price' => 'required',
'keterangan' => 'Nullable',
]);
$transaction_in = new Transaction_in();
$transaction_in->idTransaction_in = "0";
$transaction_in->Supplier_id = $request->input('supplier_name');
$transaction_in->tanggal_transaksi = $request->input('transaction_in_date');
$transaction_in->save();
$transaction_in->update(['idTransaction_in' => sprintf('TIN-%04d', $transaction_in->id)]);
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
if(count($request->device_type_name)>0){
foreach ($request->device_type_name as $item => $v) {
$data2=array(
'Transaction_in_id' => $lastid,
'DeviceType_id' => $request->device_type_name[$item],
'DeviceBrand_id' => $request->device_brand_name[$item],
'spek_device' => $request->device_spec[$item],
'harga_device' => $request->price[$item],
'jumlah_device' => $request->amount[$item],
'total_harga_device' => $request->total_price[$item]
);
Transaction_in_detail::insert($data2);
}
}
return redirect('/transactionsin')->with('success', 'Transaction success');
}
The DeviceType_id and Devicebrand_id are foreign key.
As I see you have problem in this line
$lastid=Transaction_in::create($transaction_in)->idTransaction_in;
$transaction_in is object and create method requires array to be passed in.
If everything else is correct this should work:
$lastid=Transaction_in::create($transaction_in->toArray())->idTransaction_in;
You have already save the data, but you use create also. It will create duplicate records in your DB.
I will give you a solution:
$transactionIn = Transaction_in::create([
'idTransaction_id' => '0',
'supplier_id' => $request->input('supplier_name') // why supplier name assigned supplier_id?
'tanggal_transaksi' => $request->input('transaction_in_date'),
]);
$transactionIn = tap($transaction_in)->update([
'idTransaction_in' => sprintf('TIN-%04d', $transactionIn->id)
]);
$lastId = $transactionIn->idTransaction_in;
I have a database that was not designed for Laravel. I am building a small api using Laravel. Thus I can not useLlaravel structured queries. The query is working but need to be able to retrieve the id number of an insert.
This is the insert I am using.
$results = DB::insert("
SELECT * FROM insrdata.add_user(
:assocID,
:accountID,
:firstName,
:middleName,
:lastName,
:address1,
:address2,
:city,
:state,
:zipCode,
:phone,
:email,
:birthDateMMDDYYYY,
:gradeLevelID,
:commentText
)
",
[
'assocID' => $request->input('assocID'),
'accountID' => $request->input('accountID'),
'firstName' => $request->input('firstName'),
'middleName' => $request->input('middleName'),
'lastName' => $request->input('lastName'),
'address1' => $request->input('address1'),
'address2' => $request->input('address2'),
'city' => $request->input('city'),
'state' => $request->input('state'),
'zipCode' => $request->input(''),
'phone' => $request->input(''),
'email' => $request->input('email'),
'birthDateMMDDYYYY' => $request->input('birthDateMMDDYYYY'),
'gradeLevelID' => $request->input('gradeLevelID'),
'commentText' => $request->input('commentText')
]
);
if($results) {
$return_array = array(
'p_contact_id' => "",
'p_result' => "O.K."
);
}
I need to get the id of the insert.
I think if the insert is successful, you can query for it by accountID (which i suppose unique for each inssured person) and get its id.
This is a little complex without using the Laravel structured queries, as you said. If you can tweak your query a little, and make sure you validate the input data ahead of your insert to prevent SQL injection, you should be able to use insertGetId. You'll have to do some work, but something along the lines of:
$id = DB::table('whateverYourTableNameIs')->insertGetId([
'assocID' => $request->input('assocID'),
'yourSelectField' => DB::raw("yourRawSelect"),
// etc.
]);
This is called "getting last inserted id". Here documentation in Laravel about it.
https://laravelcode.com/post/laravel-55-get-last-inserted-id-with-example
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();
I'm not sure if the title of this question is necessarily the accurate description of what I need to do, but I'll go ahead and ask my question and see what everyone thinks...
Basically, I am receiving data from a source that I have no control over, and I need to transpose it into a suitable format for inserting into my database using CakePHP. So, here's how I'm doing it:
public function submitApp($data) {
$array = array(
'Student' => array(
'name' => $data['name'],
'email' => $data['email'],
'phone' => $data['phone'],
'address' => $data['address'],
'dob' => $data['dob'],
'gender' => $data['gender']
),
'Application' => array(
'course_id' => $data['course_id'],
'question1' => $data['question1'],
'question2' => $data['question2'],
'question3' => $data['question3'],
'question4' => $data['question4'],
),
'ApplicationQualification' => $data['Qualifications']
);
// Logic to save $array goes here
}
The problem is that sometimes not all of the keys in $data will be submitted to my app but I still want my app to work with what it gets.
I know that I can wrap each key in a conditional like this:
if (!isset($data['name'])) { $data['name'] = null; }
...and then building the array, but this seems like a pretty clumsy way of doing it. Is there a more efficient way to do this?
You could use a simple ternary statement
'name' => array_key_exists('name', $data) ? $data['name'] : null
Alternatively, you can set up a default array and then merge the given values in
$defaults = [
'name' => null,
'email' => null,
// etc
];
$data = array_merge($defaults, $data);