Issue with a Laravel complex where condition. | Issue with CakePHP join - laravel-5

I have two tables :
TableA, TableB.
TableA has following columns :
id, username, password, type, TableB_id
TableB has following columns :
id, type, some_column, some_other_column
Now I need the records of TableA using TableB on the basis of TableB's id and 'type'.
I'm trying to define something like this in my model
TableA Model :
$this->belongsTo('TableB', [
'foreignKey' => 'TableB_id',
]);
TableB Model :
$this->belongsTo('TableA', [
'foreignKey' => 'id',
]);
When I print the SQL query it provides me this result :
ON
TableA.id = (TableB.id)
But I need this :
ON
TableA.TableB_id = (TableB.id)
================== Question 2 ==================
I am trying to get following query dynamically in Laravel
select * from products where (category like '%categoryOne%' OR category like '%categoryTwo%') and (brand like '%brandOne%' OR brand like '%brandTwo')
Here my columns are in array. I have tried like this :
$query = DB::table('products');
foreach($all as $category => $subCategory){
foreach($subCategory as $key => $value){
$val = '%' .$key .'%';
$users->orWhere($category, 'like', $val);
}
}
Issue with this query is that it is generating all the conditions with OR due to orWhere.
Does anyone know how to get a complex query of AND, OR conditions in Laravel?

I guess this is what you want to do. Please ignore css issues.
$(document).ready(function(){
$('.classToChangeDisable').hide();
$('.classToChange').change(function(){
$('.classToChangeDisable').hide();
$(this).siblings('.classToChangeDisable').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>
<input type="radio" name="gender" class="classToChange" /> 1st
<br />
<div class="classToChangeDisable">
<input type="radio" /> 1st Sub
</div>
<br />
</td>
<td>
<input type="radio" name="gender" class="classToChange" /> 2st
<br />
<div class="classToChangeDisable">
<input type="radio" /> 2nd Sub
</div>
<br />
</td>
<td>
<input type="radio" name="gender" class="classToChange" /> 3st
<br />
<div class="classToChangeDisable">
<input type="radio" /> 3rd Sub
</div>
<br />
</td>
</tr>
</tbody>
</table>

Related

laravel, get data by id using foreach

how do I fetch the data based on the insurance_id on the companion db? the insurance_id is dependent on another table called "insurances" if that helps. the db is this:
and the view looks like this:
here's the view:
<table class="table" id="companions_table">
<thead>
<tr>
<th>Name</th>
<th>Date of Birth</th>
<th>IC No</th>
<th>Relationship</th>
</tr>
</thead>
<tbody>
#foreach (old('companions', $companions->count() ? $companions : ['']) as $companion)
<tr id="companion{{ $loop->index }}">
<td>
<input type="text" name="companion_name[]" id="companion_name[]" class="form-control" value="{{ old('companion_name', $companion->companion_name) }}" />
</td>
<td>
<div class="input-group date" data-provide="datepicker" data-date-format="dd-mm-yyyy" data-date-today-highlight="true" data-date-end-date="0d">
<input class="form-control" type="text" name="dob[]" id="dob[]" value="{{ old('dob', $companion->dob) }}">
<div class="input-group-addon">
<span class="fa fa-calendar"></span>
</div>
</div>
</td>
<td>
<input type="text" name="ic[]" id="ic[]" class="form-control" value="{{ old('ic', $companion->ic) }}" />
</td>
<td>
<input type="text" name="relationship[]" id="relationship[]" class="form-control" value="{{ old('relationship', $companion->relationship) }}" />
</td>
</tr>
#endforeach
<tr id="companion{{ count(old('companions', $companions->count() ? $companions : [''])) }}"></tr>
/tbody>
</table>
<div class="row">
<div class="col-md-12">
<button id="add_row" class="btn btn-default pull-left">+ Add Row</button>
<button id='delete_row' class="pull-right btn btn-danger">- Delete Row</button>
</div>
my controller:
public function edit(Insurance $insurance)
{
abort_if(Gate::denies('insurance_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden');
$customers = CustomerProfile::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$products = Product::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$sales_2s = User::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), '');
$companions = Companion::all();
$insurance->load('customer', 'product', 'sales_2', 'team', 'companions');
$approvers = Role::findOrFail(3)->users()->get();
return view('admin.insurances.edit', compact('customers', 'products', 'sales_2s', 'insurance', 'approvers', 'companions'));
}
it keeps fetching all the data on the table, basically disregarding the insurance_id. how do I fix this?
All of the companions are being fetched, regardless of the insurance_id, because of the following line:
$companions = Companion::all();
If you only want companions with the current insurance_id, the quickest way would be to replace the previously mentioned line with:
$companions = Companion::where('insurance_id', $insurance->id)->get();
This should work, however the conventional way to handle this relationship in Laravel would be by adding the following function to your Insurance model:
use App\Models\Companion; // or wherever your model happens to be located
public function companions()
{
return $this->hasMany(Companion::class);
}
And replacing the line mentioned at the beginning with:
$companions = $insurance->companions;

Thymeleaf: How to fix updating #ManyToMany table

I have created a form using thymeleaf for updating books information.
Authors and Book have a #ManyToMany relationship. The problem is that when I save my changes, the #ManytoMany table (Book_Authors) row is deleted.
I am not trying to change the values of authors for the edited book, I simply want to
preserve the old ones.
I have tried saving each author ID in a 'input type = "hidden" ' since
this worked for saving values for #OneToMany relationship like
'PUBLISHER'
This works (Publisher old value is saved in database):
<div class="form-group">
<label class="col-lg-3 control-label">Publisher:</label>
<div class="col-md-8">
<input type="hidden" th:field="*{publisher.id}" />
<input class="form-control" type="text" value="" th:field="
{publisher.name}">
</div>
</div>
This doesn't work:
<div th:each = "author : ${authors}">
<input type="hidden" th:field="*{author.id}" />
</div>
<tr th:each="vehicle, itemStat : ${form.vehicles}">
<td>
<input hidden th:name="|vehicles[${itemStat.index}].id|" th:value="${vehicle.getId()}"/>
</td>
<td>
<input th:name="|vehicles[${itemStat.index}].brand|" th:value="${vehicle.getBrand()}"/>
</td>
<td>
<input th:name="|vehicles[${itemStat.index}].price|" th:value="${vehicle.getPrice()}"/>
</td>
</tr>
further reading : -
https://www.baeldung.com/thymeleaf-list
http://forum.thymeleaf.org/I-have-problem-in-binding-the-list-of-objects-contained-inside-a-object-on-the-form-using-thymeleaf-td3525038.html
and also u have to change cascadeType.ALL
if use #OneToMany use orphanRemoval=true

how to solve this error in laravel: ErrorException (E_WARNING) Invalid argument supplied for foreach()

I am creating a medicine shop invoice system . So at that process, I am creating a invoice form where customer information and invoicing information store in a two different model Customer model and Invoice model.
My invoice form view code below;
<form action="{{url('/invoice')}}" method="post">
{{csrf_field()}}
<div class="form-row">
<div class="col-md-4 col-md-offset-2">
<label for="customerName">Customer Name:</label>
<input type="text" id="customerName" name="customerName" class="form-control"><br>
<label for="address"> Address:</label>
<input type="text" id="address" name="address" class="form-control"><br>
<label for="mobile"> Mobile No.:</label>
<input type="text" id="mobile" name="mobileNumber" class="form-control"><br>
</div>
<div class="col-md-4">
<label for="invoiceNo"> Invoice No.:</label>
<input type="text" id="invoiceNo" name="invoiceNum" class="form-control"><br>
<label for="date"> Date:</label>
<input type="date" id="date" name="date" class="form-control"><br>
</div>
</div>
<hr>
<table class="table table-bordered" cellpadding="10px" cellspacing="5px">
<thead>
<th>Meidicine Name:.</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
<th style="text-align: center"><i class="fas fa-plus-square plus "></i></th>
</thead>
<tbody>
<tr>
<td>
<select name="medicineName" id="" class="form-control-sm medicineName" >
#foreach($data as $item)
<option value="{{$item->id}}">{{$item->medicineName}}</option>
#endforeach
</select>
</td>
<td><input type="number" class="form-control-sm quantity" name="quantity"></td>
<td><input type="number" class="form-control-sm price" name="price"></td>
<td><input type="number" class="form-control-sm totalAmount" name="totalAmount"></td>
<td style="text-align: center"><i class="fas fa-times"></i></td>
</tr>
<tr><td><input type="submit" class="btn btn-info btn-sm" value="ADD"></td></tr>
</tbody>
</table>
</form>
In this invoice form medicine name came from another model Medicine using laravel eloquent relationship
my InvoiceController store method code below
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
foreach($request->medicineName as $value => $key) --->error occurs
this line
{
$data = array(
'customer_id' => $id,
'medicine_id' => $value,
'invoiceNum' => $request->invoiceNum[$key],
'date' =>$request->date[$key],
'quantity' =>$request->quantity[$key],
'price' =>$request->price[$key],
'totalAmount'=> $request->totalAmount[$key]
);
Invoice::insert($data);
}
}
return back();
}
when I click ADD button to submit data two different model Customer & Invoice browser can show error look like
"ErrorException (E_WARNING)
Invalid argument supplied for foreach()"
How to solve this type of error, pls anyone can help me..
it's because $request->medicineName is just one element and not an array or collection, try it like this :
public function store(Request $request)
{
$customer = new Customer();
$customer->fill($request->all());
if($customer->save()){
$id = $customer->id;
$data = array(
'customer_id' => $id,
'medicine_id' => $request->medicineName,
'invoiceNum' => $request->invoiceNum,
'date' =>$request->date,
'quantity' =>$request->quantity,
'price' =>$request->price,
'totalAmount'=> $request->totalAmount
);
Invoice::insert($data);
}
return back();
}

Codeigniter How to populate mult icheckbox from database

<tr>
<td>Role1</td><td>
<div class="Oinput" id="Ocheckbox">
<span class="rcs_input_label"></span>
<input type="checkbox" name="roles_method_id[]" value="1" /><span class="Olabel"></span>
</div>
</td>
</tr>
<tr>
<td>Role2</td><td>
<div class="Oinput" id="Ocheckbox">
<span class="rcs_input_label"></span>
<input type="checkbox" name="roles_method_id[]" value="2" <?php echo set_checkbox('roles_method_id', '2'); ?>
</div>
</td>
</tr>
How to get past saved check boxes with same name from database in codeigniter the data is saved but can't populate from database , if there is any way to get it from database using codeigniter or even using ajax to update

Dynamically added input elements are not preserving entered data when creating new input elements

I've created a test app to learn more about asp.net mvc. The app is supposed to allow the use to add an "unlimited" number of inputs via jQuery using partial views and editor templates. I've managed to get the adding of the new input elements but I'm having issues preserving the entered data from the user when adding newer input elements.
My strongly-typed view
#model TestApp.Models.ItemViewModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.ItemName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ItemName)
#Html.ValidationMessageFor(model => model.ItemName)
</div>
<div class="editor-label">
Click to add rates
</div>
<div class="editor-field">
Add Rate
<input type="hidden" value="0" id="rateCounter" />
</div>
<br />
<span id="itemRates"></span>
<p>
<input type="submit" value="Save" />
</p>
}
My javascript
When the user clicks on the NewRate element above, I fire this jQuery to get the partial view. I also keep track of the number of rows created by the user via a hidden element rateCounter which I increment everytime the click event fires.
$("#NewRate").click(function () {
var count = parseInt($("#rateCounter").val());
$("#rateCounter").val(count + 1);
$.ajax({
type: 'GET',
url: '/Item/AddRate',
data: {
rateCount: $("#rateCounter").val()
},
success: function (data) {
$('#itemRates').html(data);
}
});
});
My controller
This accepts the number of rows to create and passes to the partial view.
public PartialViewResult AddRate(int rateCount)
{
var itemVM = new ItemViewModel { Rates = new List<ItemRatesViewModel>() };
for (int i = 0; i < RateCount; i++)
{
itemVM.Rates.Add(new ItemRatesViewModel());
}
return PartialView("_ItemRates", itemVM);
}
My strongly-typed partial view
The partial view just uses an editor template
#model TestApp.Models.ItemViewModel
#Html.EditorFor(model => model.Rates)
My editor template
The editor template basically displays each rate
#model TestApp.Models.ItemRatesViewModel
<tr>
<td>
#Html.EditorFor(model => model.Rate)
#Html.ValidationMessageFor(model => model.Rate)
</td>
<td>
#Html.EditorFor(model => model.StartDate)
#Html.ValidationMessageFor(model => model.StartDate)
</td>
<td>
#Html.EditorFor(model => model.EndDate)
#Html.ValidationMessageFor(model => model.EndDate)
</td>
</tr>
On the first click
Using Google Chrome's developer tools, I see that the response is like this. Which should be correct. When I submit the form, the model binder picks up the entered data.
<tr>
<td>
<input class="text-box single-line" data-val="true" data-val-number="The field Rate must be a number." data-val-required="*" id="Rates_0__Rate" name="Rates[0].Rate" type="text" value="0.00" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].Rate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__StartDate" name="Rates[0].StartDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].StartDate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__EndDate" name="Rates[0].EndDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].EndDate" data-valmsg-replace="true"></span>
</td>
</tr>
On the second click
The entered data on the first set of input element (index [0]) is discarded and replaced by newly initialized one since I am using $('#itemRates').html(data); in my javascript instead of $('#itemRates').append(data);. Below is what I get. When I submit the form, the model binder picks up the entered data correctly in the Rates collection of the view model.
<tr>
<td>
<input class="text-box single-line" data-val="true" data-val-number="The field Rate must be a number." data-val-required="*" id="Rates_0__Rate" name="Rates[0].Rate" type="text" value="0.00" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].Rate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__StartDate" name="Rates[0].StartDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].StartDate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__EndDate" name="Rates[0].EndDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[0].EndDate" data-valmsg-replace="true"></span>
</td>
</tr>
<tr>
<td>
<input class="text-box single-line" data-val="true" data-val-number="The field Rate must be a number." data-val-required="*" id="Rates_1__Rate" name="Rates[1].Rate" type="text" value="0.00" />
<span class="field-validation-valid" data-valmsg-for="Rates[1].Rate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__StartDate" name="Rates[1].StartDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[1].StartDate" data-valmsg-replace="true"></span>
</td>
<td>
<input data-datepicker-future="True" data-val="true" data-val-required="*" id="Rates_0__EndDate" name="Rates[1].EndDate" type="text" value="01/01/0001" />
<span class="field-validation-valid" data-valmsg-for="Rates[1].EndDate" data-valmsg-replace="true"></span>
</td>
</tr>
FINALLY, my question
Is there a way to get just the 2nd row (index [1]) in the generated response then use jQuery's append instead of replacing the whole html with the new rows? What is the correct way of doing this? I know I'm close but a little guidance would go a long way. :)
I probably wouldn't be going back to the server and getting the whole view with all the rows this way.
The way MVC parses the sent data once posting the form is the array of elements sent back (specified by the number in [] brackets in the name attribute of the elements.
The way I have done it in the past is cloned the row by jquery and used a regex function to replace the[0] with [1] and cleared the values out also. Then just append it.
This will also save you from doing a call to the server every time the add is clicked.

Resources