insert multiple selected value from laravel 5 form - mysql

I have a form in laravel 5 as below
#extends('users.home')
#section('content')
<form role="form" action="{{route('postPay')}}" method="post">
<div class="row">
<div class="col-md-12">
<fieldset class="group-border">
<legend class="group-border">Payment Record</legend>
<div class="row">
<div class="col-lg-4">
<div class="form-inline">
<label class="control-label">Current Date:</label>
<input type="text" class="date form-control" id="datepicker" name="date">
</div>
</div>
<div class="col-lg-4">
<div class="form-inline">
<!-- <label class="control-label">Month:</label> -->
<select style="width:250px" multiple="true" class="form-control input-md" id="js-example-basic-single" name="month">
<option value="january">January</option>
<option value="february">February</option>
<option value="march">March</option>
<option value="april">April</option>
<option value="may">May</option>
<option value="june">June</option>
<option value="july">July</option>
<option value="august">August</option>
<option value="september">September</option>
<option value="october">October</option>
<option value="november">November</option>
<option value="december">December</option>
</select>
</div>
</div>
<div class="col-lg-4">
<div class="form-inline">
<label class="control-label">Year:</label>
<input class="form-control input-md" type="text" name="year">
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-1">
<label for="">Customer</label>
</div>
<div class="col-lg-7">
<select class="form-control input-md" name="record_id">
#foreach($records as $record)
<option value="{{$record->id}}">{{$record->user_name}}</option>
#endforeach
</select>
</div>
<div style="float: left;" class="col-lg-4 text-left">
<div class="form-inline">
<label class="control-label">Due: </label>
<input class="form-control input-sm" type="text" name="due">
</div>
</div>
</div>
<br>
<div class="row">
<div class="col-lg-1">
<label class="control-label">Amount:</label>
</div>
<div class="col-lg-7">
<input class="form-control input-sm" type="text" name="amount">
</div>
<div class="col-lg-4">
<div class="form-inline">
<label class="control-label">Advance:</label>
<input class="form-control input-sm" type="text" name="advance">
</div>
</div>
</div>
</fieldset>
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-success btn-block">Submit</button>
</div>
<input type="hidden" name="_token" value="{{Session::token()}}"/>
</form>
#endsection
And this is the payment migration table,
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePaymentsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->increments('id');
$table->integer('record_id')->unsigned();
$table->date('date');
$table->string('month');
$table->integer('year');
$table->integer('amount');
$table->integer('advance');
$table->integer('due');
$table->dateTime('created_at');
$table->dateTime('updated_at');
$table->foreign('record_id')->references('id')->on('records');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('payments');
}
}
The 'month' field in the form is a multiple selected field made with select2 which I want to store in the database but as far as I know each record in the database does not allow multiple values.How can I make it work? Please,help.

In the multiple select month, use name as array like name="month[]" so you will receive an array with month. Then, you can iterate this array and for each month insert a record in db. You can either create insert query foreach month or use batch insert.
public function store(Request $request)
{
$inputs = $request->all();
$months = $inputs['month'];
//Multiple insert queries
foreach ($months as $month) {
Payments::create([
'date' => $input['date'],
'year' => $inputs['year']
'month' => $month,
'amount' => $inputs['amount'],
'advance' => $inputs['advance'],
'due' => $inputs['due'],
'record_id' => $inputs['record_id']
]);
}
//-------------------------------------------------//
//Batch insert, use either one
$data = [];
foreach ($months as $month) {
$data[] = [
'date' => $input['date'],
'year' => $inputs['year']
'month' => $month,
'amount' => $inputs['amount'],
'advance' => $inputs['advance'],
'due' => $inputs['due'],
'record_id' => $inputs['record_id']
]
}
DB::table('payments')->insert($data);
}
Enjoy coding :)

On submit the form select2 always return the selected options in array. You can convert the array in string using the implode so you can store the result as 'january,may' in month field.

Related

Insert all documents as per selected departments and so on

I'm trying to insert Department wise Doc in Docuploadrole table. For first department, all documents which are related to that department will be inserted and then will go for next department to do perform the same until loops ends for all departments.
Below is the screenshot of the input page:
Below is my desired output:
Controller
/*Insert into DB*/
public function DocRoleUploadRoleStore(Request $request)
{
$uploadroledoctype = $request->uploadroledoctype;
$uploadroledept = $request->uploadroledept;
foreach($uploadroledoctype as $docid) {
Docuploadrole::create([
'deptid' => $request->uploadroledept,
'docid' => $docid,
'username' => $request->uploadroleuser,
]);
}
return redirect()->back()->with('status','Upload Role Added successfully');
}
/*Document Type based on Department Dependency*/
public function DocRoleGetUploadRoleDocType(Request $request){
$cid = $request -> post('cid');
$GetUploadRoleDocRole = DB:: table('departments')
->join('doc_types','departments.deptid', '=', 'doc_types.deptid')
->whereIn('departments.deptid',explode(",", $cid))
->get();
$html = ' ';
foreach($GetUploadRoleDocRole as $list)
$html.= '<option value="'.$list ->docid.' '.$list ->deptid.'">'.$list ->deptid.' - '.$list ->docname.'</option>';
echo $html;
}
Blade View
<form action="/document-upload-role-data" method="post">
#csrf
<div class="row">
<div class="col-lg-3">
<select class="form-select form-control" name="uploadroleuser">
<option selected>Select User</option>
#foreach ($usersdata as $item)
<option value="{{$item->username}}">{{$item->username}}</option>
#endforeach
</select>
</div>
<div class="col-lg-3 d-flex">
<select class="form-select form-control" name="uploadroledept[]" multiple id="upload-role-dept">
<option selected>Select Department</option>
#foreach ($departmentDatas as $item)
<option value="{{$item->deptid}}">{{$item->deptname}}</option>
#endforeach
</select>
<input class="mx-1" style="height: 28px;" type="checkbox" name="selectalldepartment" id="upload-role-all-dept"><small style="margin-top: 2px;">All Dept.</small>
</div>
<div class="col-lg-6 d-flex">
<select class="form-select form-control" id="upload-role-doctype" type="checkbox" name="uploadroledoctype[]" multiple>
{{-- <option type="checkbox" selected="false">Document Type</option> --}}
</select>
<input class="mx-1" style="height: 28px;" type="checkbox" name="select_all" id="upload-role-all-doctype-selected"><small style="margin-top: 2px;">All Doc.</small>
</div>
<div class="col-lg-12">
<button type="submit" class="btn btn-primary float-right mt-4">Submit</button>
</div>
</div>
</form>
Route
Route::post('/document-upload-role-data'
[DocumentRoleController::class,'DocRoleUploadRoleStore']);

The form in my pop-pup window fails to submit the inserted data in Laravel

I'm trying to submit data using a pop-pup form but my submit button just closes the windows instead of saving all the data into my data base.
Everything seems to be in order but I have the impression that the form cannot read the lines of code contained in my controller
Here my codes
<div class="modal" id="exampleModalLong" tabindex="-1" role="dialog"
aria-labelledby="exampleModalLongTitle" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><b>ADD A NEW CLIENT</b></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<i data-feather="x"></i>
</button>
</div>
<div class="modal-body">
<form action="{{ route('finance.store') }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<label>Select an existing user from the database. </label>
<div class="row">
<div class="form-group col-xs-5">
<select id="Clients" class="choices form-select" title="Selectionner"
name="user_id">
<optgroup label="{{ count($Users) }} clients retrouvés">
<option value="" disabled selected>-- choisir --</option>
#foreach($Users as $User)
<option value="{{ $User->id }}">{{ $User->fullname }}</option>
#endforeach
</optgroup>
</select>
</div>
<label>Profession</label>
<div class="form-group">
<select class="choices form-select" title="Selectionner"
name="profession_id">
<option value="" disabled selected>-- choisir --</option>
#foreach($Professions as $Profession)
<option value="{{ $Profession->id }}">{{ $Profession->name }}</option>
#endforeach
</select>
</div>
<label>Phone</label>
<div class="form-group">
<input type="text" name="phone" placeholder="+243 " class="form-control">
</div>
<label>NID Type</label>
<div class="form-group">
<input type="text" name="nid_type" class="form-control">
</div>
<label>NID Photocopy</label>
<div class="row">
<div class="col-lg-2 col-xs-2">
<div class="form-group">
<img id="outputs" style="width:45px;background-color: whitesmoke;
border:1px solid #bbb;height:45px;border-radius: 2px" >
</div>
</div>
<div class="col-lg-10 col-xs-10">
<div class="form-group">
<div class="form-file">
<script type="text/javascript">
function previewImg(event) {
var outputs = document.getElementById('outputs');
outputs.src = URL.createObjectURL(event.target.files[0]);
}
</script>
<input type="file" name="nid_photocopie" accept=".png, .jpeg, .jpg"
class="form-control" id="clientImges"
onchange="return previewImg(event)">
</div>
</div>
</div>
</div>
<label>Profile Image</label>
<hr>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<img id="output" style="width:50px;height:50px;border-radius: 50px " >
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<div class="form-file">
<script type="text/javascript">
function previewImage(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
}
</script>
<input type="file" name="image" accept=".png, .jpeg, .jpg"
class="form-file-input" id="clientImgz"
onchange="return previewImage(event)">
<label class="form-file-label" for="clientImgz">
<span class="form-file-text">Choose image...</span>
<span class="form-file-button "><i data-feather="upload"></i></span>
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-light-secondary" data-dismiss="modal">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">Close</span>
</button>
<button type="submit" class="btn btn-outline-secondary ml-1" >
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Submit</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
HERE IS MY CONTROLLER
public function storeProfile(Request $request)
{
$this->validate($request, [
'user_id' => 'required',
'profession_id'=> 'required',
'nid_type'=> 'required',
'nid_photocopie'=> 'required',
]);
$slug = str_slug($request['fullname']);
$image = $request->file('image');
$image3 = $request->file('nid_photocopie');
//INSERTS PROFILE IMAGE
if (isset($image))
{
$image = $request->file('image');
$currentData = Carbon::now()->toDateString();
$fileToStore = $slug .'-'. $currentData .'-'. uniqid() .'.'. $image->getClientOriginalExtension();
if(!file_exists('uploads/MicroCredit/ClientImage'))
{
mkdir('uploads/ClientImage', 0777 , true);
}
$image->move('uploads/ClientImage',$fileToStore);
}
else {
$fileToStore = 'default.png';
}
//INSERT ID PHOTOCOPIE
if (isset($image3))
{
$image3 = $request->file('nid_photocopie');
$currentData = Carbon::now()->toDateString();
$IdToStore = $slug .'-'. $currentData .'-'. uniqid() .'.'. $image3->getClientOriginalExtension();
if(!file_exists('uploads/MicroCredit/IDs'))
{
mkdir('uploads/IDs', 0777 , true);
}
$image3->move('uploads/IDs',$IdToStore);
}
else {
$IdToStore = 'default.png';
}
$CredNew = new Client();
$CredNew->user_id = $request->user_id;
$CredNew->profession_id = $request->profession_id;
$CredNew->nid_type = $request->nid_type;
$CredNew->nid_photocopie = $IdToStore;
$CredNew->image = $fileToStore;
$CredNew->slug = $slug;
$CredNew->save();
return redirect(route('/bienvenue'));
}
HERE MY ROUTES
// ========= FINANCE - CLIENTS ======== //
Route::get('/finance/creditor', [FinanceController::class,'indexCreditor'])
->name('finance.creditor');
Route::post('/finance/store', [FinanceController::class,'store'])
->name('finance.store');
Route::post('/finance/{id}/update', [FinanceController::class,'update'])
->name('finance.update');
Route::delete('/finance/{id}/destroy', [FinanceController::class,'destroy'])
->name('finance.destroy');
HERE MY MODEL
public function storeProfile(Request $request)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $with = ['Userz'];
protected $fillable = [
'user_id',
'profession_id',
'nid_type',
'nid_photocopie',
'image',
'slug'
];
public function profesn()
{
return $this->belongsTo(Profession::class,'profession_id');
}
public function Userz()
{
return $this->belongsTo(User::class,'user_id');
}
public function getRouteKeyName()
{
return 'slug';
}
}
HERE'S MY MIGRATIONS
class CreateCreditorsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->id();
$table->integer('user_id');
$table->integer('profession_id');
$table->string('nid_type');
$table->string('nid_photocopie');
$table->string('image')->nullable();
$table->string('slug')->nullable();
$table->timestamps();
});
}
By using dd(), I was able to see which input field was causing the popup modal not to submit the data. Thanks for everyone who reached out!
dd($CredNew);

How to get the text of selected option instead of value

Here's the body of my html:
<form class="p-3">
<div class="form-group">
<label>Full Name</label>
<input id="inputName" type="text" oninput="Update(this.value, 'namec')"
class="form-control"
placeholder="Robert">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Contact Number</label>
<input id="inputNumber" type="text" oninput="Update(this.value,
'numberc')" class="form-control"
placeholder="09*********">
</div>
<div class="form-group col-md-6">
<label>Email Address</label>
<input id="inputEmail" type="email" oninput="Update(this.value, 'emailc')"
class="form-control"
placeholder="email#gmail.com">
</div>
</div>
<div class="form-group">
<label>Full Address</label>
<input type="text" class="form-control" placeholder="1234 Main St"
oninput="Update(this.value, 'addressc')">
</div>
<div class="form-row">
<div class="form-group col-md-6">
<label>Mode of Payment</label>
<select id="inputMOP" class="form-control" oninput="Update(this.value, 'mopc')">
<option selected>Select Payment</option>
<option>GCash</option>
<option>Bank Payment</option>
<option>Cash On Delivery</option>
</select>
</div>
<div class="form-group col-md-6">
<label>Shipping Option</label>
<select id="inputMOD" class="form-control" oninput="Update(this.value,
'modc')">
<option selected>Select Delivery</option>
<option>Standard Delivery</option>
<option>J&T Express</option>
<option>Ninjavan Express</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-8">
<label>Item Name</label>
<select id="inputItem" class="itemInput form-control"
oninput="Update(this.value, 'itemc')">
<option selected>Select Item</option>
<option value="155.00">Hygienix Alcohol 1L</option>
<option value="180.00">Protect Plus Alcohol 1 Gal</option>
<option value="215.00">Guardian Alcohol 1 Gal</option>
</select>
</div>
<div class="form-group col-md-4">
<label>Quantity</label>
<input id="inputQuantity" type="text" oninput="Update(this.value,
'quantityc')"
class="itemQuantity form-control" placeholder="0"><br>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-3">
<h6 class="mt-2">Total Price: ₱ </h6>
</div>
<div class="form-group col-md-3">
<input id="itemPrice" type="text" oninput="Update(this.value, 'pricec')"
class="form-control" placeholder="0" readonly>
</div>
<div class="form-group col-md-6">
<button id="placeOrder" class="btn btn-primary btn-block float-
right">Place Order</button>
</div>
</div>
</form>
Jquery to calculate the total price:
<script>
$(document).ready(function () {
$('select.itemInput').on('change', function () {
$('.itemQuantity').text($('#inputQuantity').val(0));
$('.itemQuantity').on('change', function () {
$('#itemPrice').val(
$('#inputItem').val() * $('#inputQuantity').val() + ".00"
);
});
});
});
</script>
Variable declaration to add to the database:
var cName = $('#inputName').val();
var cNumber = $('#inputNumber').val();
var cEmail = $('#inputEmail').val();
var cAddress = $('#inputAddress').val();
var cMop = $('#inputMop').val();
var cMod = $('#inputMod').val();
var cItem = $('#inputItem').find(":selected").text();
var cQuantity = $('#inputQuantity').val();
var cPrice = $('#itemPrice').val();
The problem is that I cant get the text of the selected option from the #inputItem. It only gets the value from the option. Another thing, I can't also get the total price which is under the ID of #itemPrice.
How can I get the text instead of value of #inputItem? Also, the value of #itemPrice?
EDIT:
Finally solved it!! But I have a new problem, I cant add data with a "#gmail.com" but it works when it does not have it. How can I do add data with "#email.com"?
Use the following script for the desired results. Also if you don't have any function to call onChange, kindly remove those from your input fields, from html. They will keep on throwing errors in console.
$(document).ready(function () {
$('.itemInput').on('change', function () {
// tempItemName stores the selected item name
var tempItemName = $('.itemInput option:selected').text();
totalPriceCalc();
});
$('.itemQuantity').on('change', function(){
totalPriceCalc();
});
function totalPriceCalc () {
var tempInputQty = $('#inputQuantity').val();
var tempItemPrice = $('#inputItem option:selected').val();
var tempTotalCost = (tempInputQty * tempItemPrice) + '.00';
$('#itemPrice').val(tempTotalCost);
}
});

Hierarchical Select Using Aurelia

I'm writing a mobile application using Aurelia (Cordova, Typescript, HTML5, & Bootstrap) and I need to do a hierarchical select where the selection from one SELECT list filters the options in the next SELECT list. Does anyone know how to do this in Aurelia? My code with the bindings are below. The list in selRatedItems needs to be filtered by what is selected in selCategories. Thanks for any help.
<div class="row">
<div class="form-group form-group-sm">
<label for="selCategory" class="col-sm-2 control-label">Category</label>
<div class="col-sm-10">
<select class="form-control" id="selCategory" value.bind="selectedCategory" required>
<option value="">Select a category...</option>
<option repeat.for="option of categories" model.bind="option">${option.name}</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group form-group-sm">
<label for="selRatedItem" class="col-sm-2 control-label">Rated Item</label>
<div class="col-sm-10">
<select class="form-control" id="selRatedItem" value.bind="selectedItem" required>
<option value="">Select an item...</option>
<option repeat.for="option of selectedCategory.rateditems" model.bind="option.rateditems.id">${option.rateditems.name}</option>
</select>
</div>
</div>
</div>
Here's how I resolved this...
First, I had to add a computed property in the view model that was based off of a property bound to the selCategory SELECT list from above.
Added import statement:
import { computedFrom } from 'aurelia-framework';
Added property:
#computedFrom('selectedCategory')
get rateditems() {
if (this.selectedCategory && this.selectedCategory.rateditems) {
return Object.keys(this.selectedCategory.rateditems).map(key => this.selectedCategory.rateditems[<any>key]);
}
else {
var array: any[] = [];
return array;
}
}
Then, I bound the SELECT list that is to be filtered, in this case, selRatedItem, to the computed property.
Newly bound SELECT list:
<div class="row">
<div class="form-group form-group-sm">
<label for="selRatedItem" class="col-sm-2 control-label">Rated Item</label>
<div class="col-sm-10">
<select class="form-control" id="selRatedItem" value.bind="selectedItem" required>
<option value="">Select an item...</option>
<option repeat.for="item of rateditems" model.bind="item.id">${item.name}</option>
</select>
</div>
</div>
</div>

How to disable a input field according to another select field value in bootstrap?

I am using bootstrap, I wanted to know is there something like a feature in bootstrap to do this?
<div class="form-group">
<label class="col-sm-6 control-label" for="textinput">Flooring material </label>
<div class="col-sm-6">
<select class="form-control" name="flooring_meterial">
<option value="0">-Select-</option>
<option value="1" >Earth,sand</option>
<option value="2">Dung</option>
<option value="3">Wood/planks</option>
<option value="4">Parquet or polished wood</option>
<option value="5">other</option>
</select>
<input type="text" placeholder="Other" class="form-control" name="f_m_other">
</div>
</div>
I want to activate this bellow input field, if the above select field value is "other"
Since I could not able to find a short cut for this using bootstrap, I thought to write this in native javascript.
function disable(select_val,input_id) {
var e = document.getElementById(select_val);
var strUser = e.options[e.selectedIndex].value;
if(strUser === "100"){
document.getElementById(input_id).disabled = false;
}
else{
document.getElementById(input_id).value = document.getElementById(input_id).defaultValue;
document.getElementById(input_id).disabled = true;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-sm-6 control-label" for="textinput">Principle mode of water supply</label>
<div class="col-sm-6">
<select class="form-control" name="water_supply" id="water_supply" onchange="disable('water_supply', 'w_s_other')">
<option value="0">-Select-</option>
<option value="1">Shared/ public well</option>
<option value="4">Private pipe line</option>
<option value="5">Stream/river</option>
<option value="100" >Other</option>
</select>
<input type="text" placeholder="Other" class="form-control" name="w_s_other" id="w_s_other" disabled value="">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label" for="textinput">x2</label>
<div class="col-sm-6">
<select class="form-control" name="water_supply" id="x2" onchange="disable('x2', 'x2other')">
<option value="0">-Select-</option>
<option value="1">Shared/ public well</option>
<option value="5">Stream/river</option>
<option value="100" >Other</option>
</select>
<input type="text" placeholder="Other" class="form-control" name="w_s_other" id="x2other" disabled value="">
</div>
</div>
Try using change event at select element to set input disabled to true if value of select element is "5" with .prop()
$("select").change(function() {
$("+ input", this).prop("disabled", !(this.value === "5"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div class="form-group">
<label class="col-sm-6 control-label" for="textinput">Flooring material </label>
<div class="col-sm-6">
<select class="form-control" name="flooring_meterial">
<option value="0">-Select-</option>
<option value="1" >Earth,sand</option>
<option value="2">Dung</option>
<option value="3">Wood/planks</option>
<option value="4">Parquet or polished wood</option>
<option value="5">other</option>
</select>
<input type="text" placeholder="Other" class="form-control" name="f_m_other" disabled="true">
</div>
</div>