copy all data in exists column to a new columns at Laravel - php

I have an exists data on database
NewMWU :
id
data1
data2
data3
measurementu
department_id
done_dep
1
10
10
10
measurement1
empty
default: 0
then I pass this data to some Departments Ids.
Controller :
public function storeTS(Request $request)
{
foreach( (array) $request->dep_ids as $dep_id ){
$data = new NewMWU;
$data->measurementu = $request->measurementu;
$data->department_id = $dep_id;
$data->done_dep = 2;
$data->save();
}
Session::flash('success');
return redirect()->route('newMW.index');
After I passed data that will be like this on database at same table :
NewMWU :
id
data1
data2
data3
measurementu
department_id
done_dep
1
10
10
10
measurement1
empty
default: 0
2
empty
empty
empty
measurement1
1
2
3
empty
empty
empty
measurement1
2
2
4
empty
empty
empty
measurement1
3
2
how can I copy data1,data2,data3 to a new columns that created with ids = 2,3,4 from column id = 1.
Blade page :
<form class="m-form m-form--fit" action="{{route('admin.newMW.storeTS')}}" method="POST">
{{ csrf_field() }}
<div id="divt" class="form-group m-form__group">
<div class="row">
<div class="col-sm-6">
<select class="form-control m-input" name="measurementu" required>
<option value="">chose measurement</option>
#foreach ($measurement as $s)
<option value="{{$s->measurementu}}">{{$s->measurementu}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div id="divt" class="m-form__group">
<div class="row">
<div class="col-sm-3">
<select class="form-control m-input" name="dep_ids[]" multiple required>
#foreach ($mnue2 as $d)
<option value="{{$d->id}}">{{$d->name}}</option>
#endforeach
</select>
</div>
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions">
<button type="submit" class="btn btn-success">save</button>
</div>
</div>
</form>
I tried a lot of thinks like I add inputs in blade page for data1,2,3 but that is does not work.
Hope to help me how can I pass data1,2,3 in column 1 to a new columns with a requested data.

Related

laravel 9 form validation error has space between field name

There are space comes after every character of field name while displaying errors in blade template in laravel 9 as mentioned in uploaded image
my code is mentioned as below
CODE IN HTML IS :
<form action="{{route('saveAsset')}}" method="post">
{{#csrf_field()}}
<div class="form-group">
<label for="assetTitle" class="mt-2 mb-2">{{$assetCategory->category}} TITLE :</label>
<input type="text" class="form-control" name="assetTitle" id="assetTitle" placeholder="Enter Asset Title">
</div>
<div class="inputError">#error('assetTitle') Error: {{ $message }} #enderror </div>
<input type="hidden" name="assetCateId" id="assetCateId" value="{{$assetCategory->id}}">
#if(count($attributes) > 0)
#foreach($attributes as $attribute)
<label for="assetType-{{$attribute->attr_id}}" class="mt-4 mb-2">{{$attribute->attr_title}} : </label>
<div class="form-group">
<select class="form-select" name="{{$attribute->attr_title}}" id="attribute-{{$attribute->attr_id}}" aria-label="Default select example">
<option value="">Select {{$attribute->attr_title}}</option>
#foreach($attrValues as $attrValue)
#if ($attrValue->attr_id == $attribute->attr_id && strlen($attrValue->value) > 0 )
<option value="{{$attribute->attr_id}}-{{$attrValue->value_id}}" > {{$attrValue->value}}</option>
#endif
#endforeach
</select>
</div>
<div class="inputError"> #error("{$attribute->attr_title}") Error: {{ $message }} #enderror </div>
#endforeach
#endif
<div>
<button type="submit" class="btn btn-primary mt-3 px-4">Save</button>
</div>
</form>
CODE IN CONTROLLER IS :
$fields = $req->input();
$ValidationRules=[];
foreach($fields as $fieldName=>$fieldvalue){
if($fieldName == "assetTitle"){
$ValidationRules[$fieldName] = 'required|unique:assets,title';
}else{
$ValidationRules[$fieldName] = 'required';
}
}
$req->validate($ValidationRules);
I guess you have made some changes in resources/lang/en/validation.php file.
in this or any language you have set , there is a attribute named attributes
that you can change the the attribute name displaying in error message.
because the error message of asset field is ok I do not think it's a general error . check this file and attributes or messages key in it.
Don't know if you still need help but I just had the same issue and I think it's because you might have the input names with text uppercase, laravel automaticly adds a space for each uppercase character in the name attribute when showing the errors.
For example:
name="thisModel"
Will display as:
... this Model ...
If you have:
name="MODEL"
Will display as:
... M O D E L ...
Hope this helps someone in the future x)

Two variable in one foreach

I need two variable in one foreach.
Now i'm having like this:
#php $championships = \App\Models\Championship::all(); #endphp
<div class="tour-list">
#foreach($tours as $tour)
<div class="tour-list-box row">
<input type="text" value="{{$tour->name}}" class="col-md-3 input-styles">
<input type="date" value="{{$tour->start_date}}" class="col-md-3 input-styles">
<select name="" id="" class="col-md-3 input-styles">
#foreach($championships as $championship)
#if($championship->deleted)
<option value="">select championship</option>
#else
<option value="">{{$championship->name}}</option>
#endif
#endforeach
#if($tour->championship->deleted)
#else
<option selected value="">{{$tour->championship->name}}</option>
#endif
</select>
<!-- all championships -->
<span tour_id="{{$tour->id}}" class="btn btn-sm btn-primary pull-left col-md-1 tour-remove-button"><span class="glyphicon glyphicon-remove"></span></span>
<span championship_id="{{$championship->id}}" class="btn btn-sm btn-primary pull-right col-md-1 tour-edit-input"><span class="glyphicon glyphicon-edit"></span> </span>
</div>
#endforeach
</div>
But it's repeated 2 times so i need this 2 variables $tours and $championships in one foreach.
I tried this:
#foreach(array_combine($championships, $tours) as $championship => $tour)
#endforeach
But i'm getting error ' array_combine(): Argument #1 ($keys) must be of type array, '
is it passable to have 2 variables?
Thanks for answers <3
First of all,it's not recommended to use the model directly inside the blade file,instead putt all this logic inside the controller and pass one variable to the view.
second,all eloquent are objects(collections) so you cant deal with them as array ,to treat them ass array you need $championships = \App\Models\Championship::all()->toArray()
third,array_combine — Creates an array by using one array for keys and another for its values you need to use $array = array_unique(array_merge($array1, $array2)); instead to merge 2 arrays int one array containing only unique values

How to output a value from database on selecting an option from dropdown using loop?

I am new to laravel.
I have a data set from a database which is stored in a variable product_data.
name
number_of_products
price
0-50k
2
200
51-100k
3
123
100-150k
6
345
150-200k
8
450
I want to write name as dropdown , on selecting a particular name the number of products and price should display as text . I wish to add another dropdown for quantity for each name , the quantity should be maximum of number of products.
For example: If I select a name 51-100k from the dropdown, the price 123 should display in text field and number of products 3 should display in a text filed and the quantity in dropdown should range from 1 to 3 . This fields should also save to another table in database with table name as bid_price with fields as name, number_of_products,bid_price, original_Price.
What I have tried is:
<div class="form-group row">
<label>Select Milege gap: </label>
<select class="form-select" name="mileage" id="mileage" onchange="getOption()">
{% for p in product_data %}
<option value="{{p.name}}">{{p.name}}</option>
{% endfor %}
</select>
</div>
<div class="form-group row">
<label>Avalaible Quantity: </label>
<input type="text" class="form-control" readonly name="avaialbe_qty"/>
</div>
<div class="form-group row">
<label>Quantity: </label>
<select class="form-select" name="quantity" id="quantity" >
{% for p in product_data %}
<option value="{{p.number_of_products}}">{{p.number_of_products}}</option>
{% endfor %}
</select>
</div>
<div class="form-group row">
<label for="inputBid" class="col-sm-2 col-form-label" >Enter Bid Price</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="inputBid" name="bid" />
</div>
</div>
<script>
function getOption()
{
var select = document.getElementById('mileage');
var option = select.options[select.selectedIndex];
document.getElementById('truck').value = option.value;
}
</script>
How to show the corresponding price and number of products based on select value of dropdown.?
{% for p in product_data %}
<option value="{{p.number_of_products}}">{{p.number_of_products}}</option>
{% endfor %}
This is Jinja not blade
in order to use blade
#foreach($product_data as $product)
<option value="{{$product->number_of_products}}">{{$product->number_of_products}} - ${{$product->price}}</option>
#endforeach
The below given snippet is an example to illustrate how to achieve your goal in plain php and javascript.
You may change it into Laravel Blade and front end of your choice.
Assume that you have the data as a PHP Array as given below.
<?php
$data = [
[
"name" => "0-50k",
"number_of_products" => 2,
"price" => 200,
],
[
"name" => "51-100k",
"number_of_products" => 3,
"price" => 123,
],
[
"name" => "100-150k",
"number_of_products" => 6,
"price" => 345,
],
[
"name" => "150-200k",
"number_of_products" => 8,
"price" => 450,
]
];
?>
In the HTML
<!-- Including bootstrap for styling --!>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<body>
<div class="container">
<div class="row mt-1 p-5">
<div class="text-success" id="summary"></div>
</div>
<div class="row mt-5 p-5">
<div class="col-3">
<select name="mileage" id="mileage" onchange="updatePage()" class="form-control">
<option value="">Select</option>
<?php foreach ($data as $row) : ?>
<option value="<?php echo $row['price']; ?>" data-name="<?php echo $row['name']; ?>" data-numberofprods="<?php echo $row['number_of_products']; ?>" data-price="<?php echo $row['price']; ?>">
<?php echo $row['name']; ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="col-3">
<input type="text" id="truck" value="" class="form-control" />
</div>
</div>
</div>
</body>
<script>
function updatePage() {
var summEl = document.getElementById('summary')
summEl.innerHTML = null;
var select = document.getElementById('mileage');
var selectedElem = select.options[select.selectedIndex]
var val = selectedElem.value
var outputEl = document.getElementById('truck');
if (typeof val === 'undefined' || '' === val) {
outputEl.value = '';
}
let name = selectedElem.getAttribute('data-name')
let numOfProds = selectedElem.getAttribute('data-numberofprods')
let price = selectedElem.getAttribute('data-price')
outputEl.value = price;
summEl.innerHTML = `Maximum ${numOfProds} ${name} products are available.`
}
</script>
A note of Caution:
This snippet uses the price and other details as a data-property.
This can be manipulated by the anyone. So this is less secure and not recommended to use without server side validation.
I have made this suggestion based on the limited information given in the question. The actual requirement is unknown.

Bootstrap-Select: get comma values from a Mysql column and display them automaticly inside bootstrap-select as checked

I'm working with Bootstrap-Select and I would like that some options inside this multiple dropdown list, would it be checked based on comma values from a Mysql column. I found one similar question, but I didn't find a correct way to solve my question:
Bootstrap select - Get selected Value
Below are two tables that describe my question:
colors_tbl
colorID | color |
--------+-------+
01 | Blue |
02 | Black |
03 | Green |
04 | Red |
05 | White |
-----------------
And below is the table that storage the values with comma inside column Color. The color column is a foreign key of Colors table above.
cars_tbl
carID | car | colors
------+------+------------------
01 | BMW | Red,Blue,Green
02 | GM | Red,Black,White
03 | FORD | Green,Gray,Black
--------------------------------
Based on the information above, I would like to get color values from cars_tbl on colors column (ID 03), for example, and display these values inside Bootstrap select as checked when a bootstrap modal is open.
Below is an image that show what has been described:
Below is the html code of bootstrap modal that display Bootstrap-Select inside and a jQuery function that open modal and display data using ajax results:
<div class="modal fade" id="userModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Edit Car</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="row">
<div class="col">
<label>Car</label>
<input type="text" name="car" id="car" class="form-control"/>
</div>
<div class="col">
<div class="form-group">
<label>Colors</label>
<?php
include 'pdo_connection.php';
$stmt = $connection->prepare('SELECT * FROM colors_tbl');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<select class="selectpicker form-control" name="colors[]" id="colors" data-actions-box="true" multiple>
<?php foreach($results as $row): ?>
<option value="<?= $row['colorID']; ?>"><?= $row['color']; ?></option>
<?php endforeach ?>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-warning" value="" />
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#car').val(data.car);
$('#colors').val(data.colors);
$('#user_id').val(user_id);
$('#action').val("Edit Car");
$('#operation').val("Edit");
}
})
});
</script>
And a php script (fetch_single.php) that fetch data when modal above is open:
<?php
include 'pdo_connection.php';
if(isset($_POST["user_id"]))
{
$output = array();
$statement = $connection->prepare(
"SELECT * FROM cars = '".$_POST["user_id"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["car"] = $row["car"];
$output["colors"] = $row['colors'];
}
echo json_encode($output);
}
?>
To try to solve this doubt, i tried to put this code below after variable $output = array(); of fetch_single script above:
$array = array($row['colors']);
$colors = implode(",", $array);
And replace this line:
$output["colors"] = $row['colors'];
to this:
$output["colors"] = $color;
But no success.
UPDATED
I found a method that Bootstrap-select use to get values and display inside dropdown list. The method is:
$('.selectpicker').selectpicker('val', ['value 1','value 2']);
In this case, i put this selectpicker method inside ajax success and i dont know how can i get colors values from my php script that send results in JSON format to Ajax. If i replace the values 'value 1' and 'value 2' to 'data.colors' inside brackets above, i didn't get nothing when modal is opened:
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#car').val(data.car);
$('#colors').selectpicker('val', [data.colors]);
$('#user_id').val(user_id);
$('#action').val("Edit Car");
$('#operation').val("Edit");
}
})
How can i put colors values from JSON format and put indide selectpicker.('val', [])?
I dont understand the method of some moderators. I found a solution myself to solve my doubt and probably hundreds of doubts of programmers who might have the same doubt. Less bureaucracy, please.
To be more specific, according to some incomprehensible moderators:
I solve my question using javascript string split() method. The split() method is used to split a string into an array of substrings, and returns a new array.
Tip: If an empty string ("") is used as the separator, the string is split between each character.
Note: The split() method does not change the original string.
$('.selectpicker').selectpicker('val', data.color.split(','));
Is that good now? Free hugs for all lords of stackoverflow!!!

Display the dropdown text using laravel

I'm working on a reporting page using php Laravel framework. I select the options from the comboboxes, these values are sent to the controller to replace them in some queries used to display the reports.
When I click the submit button, the page refreshes and the name shown is the last element of the dropdown.
My Controller:
$negocioDive = DB::table('ma_leads_reporte')
->selectRaw('NEGOCIO, year(FEC_CREACION) as AÑO')
->groupBy('NEGOCIO', 'AÑO')
->get()->toArray();
$selectFecha = DB::table('param_fecha')
->selectRaw('mesNum, mesNom')
->groupBy('mesNum', 'mesNom')
->get()->toArray();
$año = $request ->input('año');
$mes = $request -> input('mes');
$negocio = $request -> input('negocio');
//Solicitud de Cotización versus mes anterior
$mesAnt = DB::table('ma_leads_reporte')
->selectRaw('count(*) as C, day(FEC_CREACION) AS DIA, monthname(FEC_CREACION) AS MES')
->whereMonth('date_identified', '=', $mes-1)
->whereYear('date_identified', '=', $año)
->groupBy('MES', 'DIA')
->get()->toArray();
$vscont = array_column($mesAnt, 'C');
$antMes = array_column($mesAnt, 'MES');
$dia = array_column($mesAnt, 'DIA');
My View:
<div class="container">
<div class="row justify-content-center">
<div class="content mt-3">
<div class="animated fadeIn">
<div class="col-lg-8">
<div class="card">
<div class="card-header">
<form action="{{route('reportes')}}" method="GET" id="fecha">
{{Form::label('', 'Año')}}
<select id="año" name="año">
#foreach($negocioDive as
$negocioD)
<option value="{{$negocioD->AÑO}}"
selected="selected">{{$negocioD->AÑO}}</option>
#endforeach
</select>
{{Form::label('', 'Mes')}}
<select id="mes" name="mes">
#foreach($selectFecha as $fecha)
<option value="{{$fecha->mesNum}}" name="{{$fecha->mesNom}}">{{$fecha->mesNom}}</option>
#endforeach
</select>
{{Form::label('', 'Negocio')}}
<select id="negocio" name="negocio" >
#foreach($negocioDive as $negocioD)
<option value="{{$negocioD->NEGOCIO}}" selected="selected">{{$negocioD->NEGOCIO}}</option>
#endforeach
</select>
<button type="submit"class="btn btn-default" id="filter">Filtrar
<i class="fa fa-filter"></i>
</button>
</form>
<?php if(isset($_GET['año']) && isset($_GET['mes']) && isset($_GET['negocio'])){
echo "<h4> Año: $año | Mes: {$fecha->mesNom} | Negocio: $negocio </h4>";
}?><!--
<p id="mesJS"></p> -->
</div>
</div>
</div>
After receiving the request variables, it should show the correct values instead of the last index of the dropdown.
What can I do?
dropdown options:
After submit:
The reason it is showing the last index of the dropdown is that you are looping on your various items and creating your options within each select box with 'selected' overwritten every time all the way to the last one in the loop.
To fix this, you'll need to add some type of conditional on the option box to tell it if the loop item is the correct selected one. If the new model has the key within this loop, then, and only then, make it selected. Something like this (You'll need to make this code your own):
#foreach($negocioDive as $id=>name)
<option value="{{$id}}" {{$theThingYouAreSelecting->id === $id?"selected":''}}>$name</option>
#endforeach
NOTE - I'm assuming you are sending a key->value array to the foreach as this is what the option expects - the key would be the id and the value would be the name for the item.
Once you get this working, I strongly recommend looking at LaravelCollective HTML - it binds the model to the form and automates a huge chunk of the conditionals.

Categories