how to save multiple select in laravel 8? - laravel

how to save multiple selcet in laravel when I try the script below, not to save
this store in controller
public function store(Request $request)
{
$id = $request->id;
$post = Rek_medik::updateOrCreate(['id' => $id],
[
'kode_rekmed' => $request->kode_rekmed,
'kode_register' => $request->kode_register,
'kode_pasien' => $request->kode_pasien,
'nama_pemeriksa' => $request->nama_pemeriksa,
'tgl_rekmed' => Carbon::now(),
'anamnesis' => $request->anamnesis,
'pemeriksaan' => $request->pemeriksaan,
'resep' => $request->resep,
]);
return response()->json($post);
}
this is code in view
<div class="form-group">
<label for="resep">Resep</label>
<select class="select2bs4" id="resep" multiple="multiple" name="resep[]" data-placeholder="Select a State"
style="width: 100%;">
#foreach($obat as $row)
<option value="{{$row->kd_obat }}" >{{$row->kd_obat }}</option>
#endforeach
</select>
</div>

Why do not you try looping through your multiple select value and save the array's element: Like this : foreach($request->resep as $item){..then save your data here..}.

i think you should use 'save' function
public function store(Request $request)
{
$id = $request->id;
$post = Rek_medik::updateOrCreate(['id' => $id],
[
'kode_rekmed' => $request->kode_rekmed,
'kode_register' => $request->kode_register,
'kode_pasien' => $request->kode_pasien,
'nama_pemeriksa' => $request->nama_pemeriksa,
'tgl_rekmed' => Carbon::now(),
'anamnesis' => $request->anamnesis,
'pemeriksaan' => $request->pemeriksaan,
'resep' => $request->resep,
]);
$result = $post->save();
return response()->json($post);
}

Well, u can modify your array first before save it to database. I assume your resep column type is varchar. Here's my solution
$id = $request->id;
foreach($request->resep[] as $r){
$resep[] = $r;
}
$post = Rek_medik::updateOrCreate(['id' => $id],
[
'kode_rekmed' => $request->kode_rekmed,
'kode_register' => $request->kode_register,
'kode_pasien' => $request->kode_pasien,
'nama_pemeriksa' => $request->nama_pemeriksa,
'tgl_rekmed' => Carbon::now(),
'anamnesis' => $request->anamnesis,
'pemeriksaan' => $request->pemeriksaan,
'resep' => json_encode($resep),
]);
return response()->json($post);
json_encode function is to convert $resep array to string. You can change it back to array with json_decode function
json_decode($resep);

Related

How do I set the old() value of a form_dropdown in Codeigniter 4?

I've got a form in Codeigniter 4 and I'm using the form helpers to build the form.
When I use a form_input I can reload the submitted values of the form using the old() method. Like below.
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Number</span>
<?php
$current_membership_options = [
'id' => "membership_number",
'name' => "membership_number",
'class' => "form-control",
'type' => 'text'
];
echo form_input($current_membership_options, old('membership_number'))
?>
I've tried a couple of different options but I can't get it to repopulate with a form_dropdown.
THE VIEW
<span class="input-group-text" id="inputGroup-sizing-sm">Membership Type</span>
<?php
$membership_type_option = [
'id' => 'membership_type',
'name=' => 'membership_type',
'class' => 'form-select ',
'type' => 'text'
];
echo form_dropdown($membership_type_option, $membership_type, old('membership_type'));
?>
I get $membership_type from the user controller.
public function new(): string
{
$user = new User;
$data = $this->model->getMemberships();
return view('Admin/Users/new', [
'user' => $user,
'membership_type' => $data
]);
}
And the model
/**
* #throws Exception
*/
public function getMemberships(): array
{
$result = $this->db->query('select * from membership_type')->getResultArray();
$dropdown = array();
$dropdown['0'] = 'Please Select';
foreach ($result as $r)
{
$dropdown[$r['id']] = $r['type'];
}
return $dropdown;
}
Thanks in advance.

Send Email with multiple images in Laravel9

I'm having problem that I would like to send Email with multiple images in Laravel9.
I wrote below code.
My goal is send Email with multiple images and
sametime each image file name stores into mysql's 'fileattach' column as photo1, photo2, photo3(one line)
Could someone correct my code please?
blade file
<div class="col-sm-6">
<input type="file" name="files[]" accept="file_extension|image/*|media_type" multiple>
</div>
Controller
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),custom name
'mime' => $file->getMimeType())
);
}
}
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
});
You are almost there, need to put the attachment code into callback method to mail.
public function saveContact(Request $request) {
$this->validate($request, [
'name' => 'required',
]);
//Get the $files array here
$files = [];
$contact = new Contact($request->all());
$contact->save();
\Mail::send('admin_email_tpl', //admin tpl
array(
'sno' => $request->get('sno'),
'name' => $request->get('name'),
'email' => $request->get('email'),
'files' => $request->post('files'),
), function($message) use ($request, $files)
{
$message->from('123#123foobar.com');
$message->to('123#123foobar.com');
$message->subject('Thank You');
if(count($files) > 0) {
foreach($files as $file) {
$message->attach($file->getRealPath(), array(
'as' => $file->getClientOriginalName(),//custom name
'mime' => $file->getMimeType())
);
}
}
});
}

Laravel update request validation not working on 9.x

I have create a validation request file on request folder. It working fine in new insert. But when i update, it's not working also i pass the unique $id but not working.
a. Resource controller update method
public function update(KlassNameRequest $request, $id)
{
$validated = $request->validated();
KlassName::where('id', $id)->update($validated);
}
b. Validation code
public function rules()
{
return [
'name' => 'required|unique:klass_names|max:128,' . $this->id,
'ref' => 'required|unique:klass_names|numeric|between:1,999,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
}
This message shows me when i update
return [
'name' => 'required|unique:klass_names,' . $this->id.'|max:128',
'ref' => 'required|unique:klass_names,' . $this->id.'|numeric|between:1,999',
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
Just try this one
'name' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('name', $this->name);
})],
'ref' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('ref', $this-> ref);
})],
Hope it will solve the problem 😊
I have solve my problem in this way -
a. Add extra input hidden field passing id for $request method. Because my route is resource group route -
<form action="{{ route('adm.kls.update', $kls->id) }}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{ $kls->id }}">
</form>
b. Some editing in validation code.
public function rules() {
return [
'name' => 'required|max:128|unique:klass_names,name,' . $this->id,
'ref' => 'required|numeric|between:1,999|unique:klass_names,ref,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
];
}
done.

why my updateOrInsert doesn't work laravel

I use updateOrInsert to avoid duplicate data, why doesn't the Update function work and always insert data?
foreach($datas as $data){
DB::table('users')->updateOrInsert([
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
}
Check out [updateOrInsert] this documentation (https://laravel.com/api/6.x/Illuminate/Database/Query/Builder.html#method_updateOrInsert). You need two parameters. One is the matching attributes (i.e., the attributes you would use to identify your record in case it exists), the other is your array (the new values you wish to insert or update the record with).
updateOrInsert(array $attributes, array $values = [])
Example
DB::table('users')->updateOrInsert(
[
'user_connect_id' => $user->connect_id
],
[
'user_connect_id' => $user->connect_id,
'description' => $data['description'],
'created_by' => $login->name,
'modified_by' => $login->name,
'created_at' => Carbon::now(),
]);
There are two arguments in updateOrInsert method.The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs containing the columns to be updated.
For e.g :
DB::table('users')
->updateOrInsert(
['email' => 'john#example.com', 'name' => 'John'],
['votes' => '2']
);
Check this link for syntax : Laravel Doc
// Inseart code
public function create()
{
return view('admin.category.create');
}
public function store(Request $request)
{
$this->validate($request,[
'name' => 'required'
]);
$category = new Category();
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Saved','Success');
return redirect()->route('admin.category.index');
}
// Update code
public function edit($id)
{
$category =Category::find($id);
return view('admin.category.edit',compact('category'));
}
public function update(Request $request, $id)
{
$this->validate($request,[
'name' => 'required|unique:categories'
]);
$category = Category::find($id);
$category->name = $request->name;
$category->slug = str_slug($request->name);
$category->save();
Toastr::success('Category Successfully Updated','Success');
return redirect()->route('admin.category.index');
}

how can i use setOpion() and getOption() method in laravel?

i am trying to first set in controller setOption(value, valuename) in controller and store in database and use it as getOption in views
but not working .
Here is my controller =>
public function edit(Request $request)
{
mpc_m_c($request->server('SERVER_NAME'));
$options = Config::all()->pluck('value','name');
$tzlist = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
return view('admin.system-settings', compact('options', 'tzlist'));
}
public function update(Request $request)
{
$this->validate($request, [
'app_name' => 'required',
'currency_symbol' => 'required',
'currency_code' => 'required',
'date_format' => 'required',
'home_page_description' => 'required',
'recaptcha_private_key' => 'required',
'minimum_deposit_amount' => 'required',
'home_page_meta' => 'required',
'notify_email' => 'required'
]);
if ($request->hasFile('logo')) {
$file = $request->file('logo');
$fileArray = array('logo' => $file);
$rules = array(
'logo' => 'mimes:png|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['logo' => $errors['logo']]);
} else {
$logo = Storage::putFile('images', $request->file('logo'));
setOption('logo', $logo);
}
}
if ($request->hasFile('banner')) {
$file = $request->file('banner');
$fileArray = array('banner' => $file);
$rules = array(
'banner' => 'mimes:png,jpg,jpeg|required|' // max 10000kb
);
$validator = Validator::make($fileArray, $rules);
if ($validator->fails()) {
$errors = $validator->errors()->getMessages();
return redirect()
->back()
->withErrors(['banner' => $errors['banner']]);
} else {
$banner = Storage::putFile('images', $request->file('banner'));
setOption('banner', $banner);
}
}
setOption('app_name', $request->input('app_name'));
setOption('currency_symbol', $request->input('currency_symbol'));
setOption('currency_code', $request->input('currency_code'));
setOption('date_format', $request->input('date_format'));
setOption('home_page_description', $request->input('home_page_description'));
setOption('recaptcha_public_key', $request->input('recaptcha_public_key'));
setOption('recaptcha_private_key', $request->input('recaptcha_private_key'));
setOption('minimum_deposit_amount', $request->input('minimum_deposit_amount'));
setOption('home_page_meta', $request->input('home_page_meta'));
setOption('module_support_enabled', $request->input('module_support_enabled'));
setOption('module_api_enabled', $request->input('module_api_enabled'));
setOption('module_subscription_enabled', $request->input('module_subscription_enabled'));
setOption('theme_color', $request->input('theme_color'));
setOption('background_color', $request->input('background_color'));
setOption('language', $request->input('language'));
setOption('display_price_per', $request->input('display_price_per'));
setOption('admin_layout', $request->input('admin_layout'));
setOption('user_layout', $request->input('user_layout'));
setOption('panel_theme', $request->input('panel_theme'));
setOption('anonymizer', $request->input('anonymizer'));
setOption('front_page', $request->input('front_page'));
setOption('show_service_list_without_login', $request->input('show_service_list_without_login'));
setOption('notify_email', $request->input('notify_email'));
setOption('currency_separator', $request->input('currency_separator'));
setOption('timezone', $request->input('timezone'));
Session::flash('alert', __('messages.updated_logout_needed'));
Session::flash('alertClass', 'success');
return redirect('/admin/system/settings');
}
route =>
Route::get('/system/settings', 'ConfigController#edit');
Route::put('/system/settings', 'ConfigController#update');
error =>
"Call to undefined function App\Http\Controllers\Admin\setOption()"
and view =>
<div class="form-group{{ $errors->has('home_page_meta') ? ' has-error' : '' }}">
<label for="home_page_meta" class="control-label">meta tags</label>
<textarea
style="height: 150px;"
class="form-control"
data-validation="required"
rows="5"
id="home_page_meta"
name="home_page_meta"> <?php echo e($options['home_page_meta']) ?></textarea>
</div>
use =>
getOption('valuename')
And by this things he is using the function getOption(''valuename) anywhere in the entire application ... i really dont want use it but just curious How he is using this things even there's no laravel build in funtion for this name?
*Note : Please don't judge me , I just want to know ..thnaks
anybody got idea how do i use it ?

Resources