I can update text field of a form but i can not update checkbox field,option field and file field in Laravel 5.2. I i going to update then i can see all text value is perfectly shown in update blade view but in option field, checkbox field i see it is default value its don't comes from database. Again if i update with another option then its not saving.What i have tried so far:
My Controller:
public function update(Request $request, $id=0)
{
//
$id = $request->input("id");
$product = Product::find($id);
$product->product_name = $request->input('product_name');
$product->product_storage = $request->input('product_storage');
$product->product_percentage = $request->input('product_percentage');
$product->can_draw = $request->input('can_draw');
$product->real_price = $request->input('real_price');
$product->product_image = $request->input('product_image');
$product->save();
$request->session()->flash('alert-info', 'Product Successfully Updated!');
return Redirect::to('admin/product/all');
}
My update.blade.php View:
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.can_be_draw') }}</label>
<div class="col-md-9">
<div class="input-icon">
<i class="fa fa-money" aria-hidden="true"></i>
<select name="can_draw" class="form-control">
<option value="{{ $product->can_draw }}">{{ trans('common.open') }}open</option>
<option value="{{ $product->can_draw }}">{{ trans('common.close') }}close</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">{{ trans('common.real_prize') }}</label>
<div class="col-md-9">
<div class="input-icon">
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}"> {{ trans('common.yes') }}yes
<input type="radio" class="form-control" name="real_price" value="{{ $product->real_price }}" checked="checked"> {{ trans('common.no') }}no
</div>
</div>
</div>
<div class="form-group">
<label for="exampleInputFile" class="col-md-3 control-label">{{ trans('common.product_picture') }}</label>
<div class="col-md-9">
<input type="file" id="exampleInputFile" name="product_image" value="{{ $product->product_image }}">
<small>{{ trans('common.pic_summery') }}</small>
</div>
</div>
Just use this:
<input type="radio" {{$product->can_draw == 'Yes' ? 'checked' : ''}} class="form-control" name="real_price" value="Yes"> {{ trans('common.yes') }}yes
<input type="radio" {{$product->can_draw == 'Yes' ? '' : 'checked'}} class="form-control" name="real_price" value="No" > {{ trans('common.no') }}no
EDIT
I have edited the above*
You should change the value to Yes and No and use this to check if the value saved is Yes or No. It does not matter how much is real_price
your option field have same value ({{ $product->can_draw }})
<option value="value1"{{( $product->can_draw=='value1'?selected)}}>{{ trans('common.open') }}open</option>
<option value="value2 " {{( $product->can_draw=='value1'?selected)}}>{{ trans('common.close') }}close</option>
and for file field must use file not input:
$product->product_image = $request->file('product_image');
You just can save option value by requesting from select name.
In your example:
select name = "can_draw"
Just save value from request:
$product->can_draw = $request->can_draw;
For checkbox same:
$product->real_price = $request->real_price;
Not necessary indicate input() helper in request.
To retrieve all value for option and check box value, please use foreach methods:
#foreach($can_draws as $can_draw)
<option value="{{ $can_draw->id }}">{{ $can_draw->name}}</option>
#endforeach
Related
i have a multiple product when i get the default value of that product, but when i get that value in input field the default value doesn't show ?
<x-filament::page>
<form wire:submit.prevent="submit">
<div>
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
</div>
<select wire:model="user_type">
<option value="">Select User Type.....</option>
<option value="admin">Admin</option>
<option value="distributor">Distributor</option>
<option value="retailer">Retailer</option>
</select><br><br>
<input wire:model="name" type="text" placeholder="Name"><br><br>
<input wire:model="email" type="email" placeholder="Email Address"><br><br>
<input wire:model="password" type="password" placeholder="Password"><br><br>
<div align = "center">Products</div>
** #foreach($product as $val)
<br><br> {{ $val->name }} :
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
#endforeach<br><br>**
<button type="submit">
Submit
</button>
</form>
</x-filament::page>
Check these screencasts. They are very helpful! https://laravel-livewire.com/screencasts/data-binding
<input type="number" wire:model="default_price" value = "{{$val->default_price}}">
Livewire doesn't use value attribute!
If you want to update Product->default_price, you can use https://laravel-livewire.com/docs/2.x/properties#binding-models or if you want to only output the default_price, then remove wire:model.
Also #foreach($products as $val) $products should be plural,
and $val should be $product, because it is a product variable. Naming is important, if you don't want to confuse yourself and others constantly.
the whole idea is that when a user click on checkbox and save, the form should be submitted with an array containing the checked values, and save them in the database as single row for each value. i don't know if this is possible but i'm sure you guys have a solution or can help me?
and here's my form:
<div class="">
<form style="width: 70%" method="POST" action="{{ URL('/admin/projects/services/save') }}"
enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id" value="{{ #$id }}">
<input type="hidden" name="projectid" id="projectid" value="{{ #$projectid }}">
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Selected Services: <span class="red">*</span></p>
</div>
<div class="col-9">
<input type="text" id="selectedServices" name="selectedServices" value="" readonly>
</div>
</div>
<div class="row topSpacer">
<div class="col-3">
<p class="bold">Select a service: <span class="red">*</span></p>
</div>
<div class="col-9">
#foreach ($services as $service)
<input type="checkbox" name="service" value="<?php echo stripslashes($service->id); ?>">
<label for="service"><?php echo stripslashes($service->name); ?></label>
<br>
<hr>
#endforeach
#error('service')
<span class="text-danger">{{ $message }}</span>
#enderror
</div>
</div>
<div class="row topSpacerHuge">
<div class="col-12 textRight">
<button type="button"
onclick="window.location='{{ url('admin/projects/services/index/'.$projectid) }}'"
class="goBackBtn">Cancel</button>
<input class="saveBtn" id="saveBtn" type="submit" value="Save">
</div>
</div>
</form>
</div>
and my script to get checkboxes value:
<script>
$(function() {
$("input:checkbox[name='service']").click(function() {
$value = [];
$.each($("input:checkbox[name='service']:checked"), function() {
$value.push($(this).val());
$array = $value.join();
});
// console.log(value.join(", "));
$("#selectedServices").val($array);
})
});
</script>
for implementing checked values I recommend to use the select tag
and you can give A name attribute with [] and it will collect all of your data
for example , look at my project's file which I'm trying to collect name of some users :
<select name="users[]" id="example-with-maxHeight" class="multiselect-group" multiple >
#foreach($users as $user)
<option #if($user->average < $averageParticipate )class="alert-danger" #endif value="{{$user->id}}">{{$user->name}} - {{$user->average}}</option>
#endforeach
</select>
have attention to users[] in name attribute
now in your request you can access all of your checked items .
if we look at your code ,can be some thing like this :
<label for="service"><?php echo stripslashes($service->name); ?></label>
<select name="services[]" id="" class="multiselect-group" multiple >
#foreach($users as $user)
<option value = "{{$sevice->id}}"> <?php echo stripslashes($service->name); ?></option>
#endforeach
</select>
now in your controllers you can access them :
request->get('services');
it will give you back an array of selected items .
Notice that id attribute helps me to interact with my java script code
you can rename it to yourselves .
I have created a form where in many cases some fields are not displayed until user select a certain option that will make the particular field displayed, this is controlled by HTML onchange Event Attribute with functions in script. To this point everything works fine.
Problem:
In the Request class I am implementing some rules for validation , for all displayed fields and for particular none displayed fields if only their options are selected then they should be validated. In my case I have 8 of this none displayed fields are a_text, b_text, c_text, d_text, e_text, f_text,g_text, h_text. If this fields were 2 it would be easy to write an If statement to choose which should be validated and which should not be validated like below:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
class StoreSectionERequest extends FormRequest
public function rules(Request $request)
{
$a = $request->a;
$b = $request->b;
if($a==5 && $b==3){
return [
//for none displayed fields only validate the below
'a_text' =>'required',
'b_text' =>'required',
//..and other displayed fields will be valuated.
];
}elseif(!$a==5 && $b==3){
return [
//for none displayed fields only validate the below
'b_text' =>'required',
//..and other displayed fields will be valuated.
];
}elseif($a==5 && !$b==3){
return [
//for none displayed fields only validate the below
'a_text' =>'required',
//..and other displayed fields will be valuated.
];
}
// in case all none displayed field are not selected only check other fields below
return [
// validaying all none displyed field here]; }}
In my case I have 8 fields which are none displayed, of which I have to handle all cases of fields if it's selected and not, this will lead to 100's or a lot of if...elseif..statements. What is the wright approach to handle this kind of task.
Form
<form method="POST" action="{{ route('......') }}">#csrf
<div class="row">
<div class="col-md-5" id="lackingSkills">
<label for="">Which skills and competencies graduates are lacking? </label>
<select name="a" multiple="multiple" id="skills" class="form-control select2 #error('a')
is-invalid
#enderror" onchange="myFunction()">
<option value="1" #if (old('a')=="1" ) {{ 'selected' }} #endif>Information and communication skills</option>
<option value="2" #if (old('a')=="2" ) {{ 'selected' }} #endif>Interpersonal skill</option>
<option value="3" #if (old('a')=="3" ) {{ 'selected' }} #endif>System management skills</option>
<option value="4" #if (old('a')=="4" ) {{ 'selected' }} #endif>Innovation skills</option>
<option value="5" #if (old('a')=="5" ) {{ 'selected' }} #endif>Others. Specify</option>
</select>
<small class="text-primary">If necessary, choose more than one option.</small>
#error('a') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6" id="skillReason" {!! $errors->has('a_text') || old('a') == 5 ? '':' style="display: none"' !!} >
<div class="form-floating mb-3">
<textarea rows="2" class="form-control #error('a_text')#enderror" name="e2_10" id="skillReason" placeholder="Type here.."></textarea>
</div>
</div>
<div class="col-md-6">
<select name="b" id="b" class="form-control" onchange="myFunction2()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('b')=="1" ) {{ 'selected' }} #endif>Most of them match the requirements</option>
<option value="2" #if (old('b')=="2" ) {{ 'selected' }} #endif>Only some match the requirements</option>
<option value="3" #if (old('b')=="3" ) {{ 'selected' }} #endif>Other, specify</option>
</select>
#error('b') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6 mt-2" {!! $errors->has('e3_5') || old('b') == 3 ? '':' style="display: none"' !!} >
<div class="form-floating mb-3">
<textarea rows="2" class="form-control" id="b_text" name="b_text" placeholder="Type here.."></textarea>
<label for="floatingInput" id="specify">Specify here..</label>
</div>
</div>
<div class="col-md-6">
<select name="c" id="graduatesPreference" class="form-control" onchange="myFunction3()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('c')=="1" ) {{ 'selected' }} #endif>Yes</option>
<option value="2" #if (old('c')=="2" ) {{ 'selected' }} #endif>No</option>
</select>
#error('c') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-6" id="preferenceReason" {!! $errors->has('c_text') || old('c') == 1 ? '':' style="display: none"' !!}>
<label for="">Provide the reason, why you have a preference for a specific university?</label>
<textarea name="c_text" id="" rows="3" class="form-control" placeholder="Provide the reason here ..."></textarea>
</div>
<div class="col-md-6">
<select name="d" id="qualification" class="form-control #error('d')is-invalid #enderror" onchange="myFunction4()">
<option value="" selected disabled>Select</option>
<option value="1" #if (old('d')=="1" ) {{ 'selected' }} #endif>Bachelor’s degree</option>
<option value="2" #if (old('d')=="2" ) {{ 'selected' }} #endif>Post-graduate</option>
<option value="3" #if (old('d')=="3" ) {{ 'selected' }} #endif>Other, specify</option>
</select>
#error('d') <span class="invalid-feedback" role="alert">{{ $message }}</span> #enderror
</div>
<div class="col-md-12" id="d_text" {!! $errors->has('d_text') || old('d') == 3 ? '':' style="display: none"' !!}>
<label for="">Explain why?</label>
<textarea name="d_text" id="d_text" rows="3" class="form-control" placeholder="Provide the reason here ..."></textarea>
</div>
////.............others fields like e,f,g,h, all have the same functionality like the above ones.
<div class="action-button d-flex justify-content-center bg-white pt-2 pb-2">
<button type="submit" class="btn btn-success">Save</button>
</div>
</div>
</form>
<script>
/// various function for onchange
myFunction()
myFunction2()
myFunction3()
myFunction4()
</script>
My question: what is the wright approach to handle the above scenario without writing 100's of if..elseif statements. Thanks in advance.
In form validation u have rules like required with or without, u can see more here
Little bit lower on the docs u can see Conditionally Adding Rules
So basically u will be doing same validation but without too much mess in your code.
I am beginner in Laravel. I make my project in Laravel 8.
I have this code:
#foreach($productIngredients as $productIngredient)
#php
if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true){
$item = \App\Models\SelectedProductIngredient::where('product_id', $product->id)->where('ingredient_id', $productIngredient->id)->first();
$weight = $item->weight;
} else {
$weight = null;
}
#endphp
<div class="col-6">
<div class="form-check py-2">
<input id="productIngredientId-{{ $productIngredient->id }}"
class="form-check-input enableInput" style="margin-top:10px"
name="productIngredient[]" type="checkbox"
value="{{ $productIngredient->id }}"
#if($selectedProductIngredients->contains('ingredient_id', $productIngredient->id) === true) checked #endif>
<label class="form-check-label" for="flexCheckChecked">
{{ $productIngredient->name }} [{{ $productIngredient->short_name }}]
</label>
<input id="productIngredient-{{ $productIngredient->id }}" type="text"
name="productIngredient-{{ $productIngredient->id }}" maxlength="10"
class="form-control weight-input weightMask"
style="width:100px;display: inline; margin-left:20px" placeholder=""
value="{{ $weight }}">
</div>
</div>
#endforeach
It's work fine.
I would like there to be 2 records in 1 row.
So I would like to add at the beginning and close div in case of the last record
How can I do this?
Please help me.
Do you know about the Laravel collection? It can help you.
You can use chunk method, it breaks the collection into multiple, smaller collections of a given size:
#foreach($productIngredients->chunk(2) as $chunk)
<div class="row">
#foreach($chunk as $productIngredients)
<div class="col-6">
...
</div>
#endforeach
</div>
#endforeach
I'm building a task list where I can add and delete fields dynamically for each user. The problem I have, is saving the data from the checkbox.
I'm using the following code:
<form>
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
#endforeach
/*The JS will add the new items here. JS example:*/
<div class="col-md-9">
<input id="taskfield" name="dynamic[]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
</form>
For saving it dynamically, I'm using this in my controller:
DB::table('tasks')->where('user_id', '=', $_POST['uid'])->where('week', '=', $_POST['week'])->where('year', '=', $_POST['year'])->delete();
if(isset($_POST['dynamic'])){
$takenvdweek = $_POST['dynamic'];
$finished = $_POST['check'];
var_dump($finished);
foreach($takenvdweek as $key => $value) {
DB::insert('insert into tasks (name, finished, user_id, week, year) values (?, ?, ?, ?, ?)', array($value, $finished[$key], $_POST['uid'], $_POST['week'], $_POST['year']));
}
}
So my Saving method requires always a value for the checkbox, 0 when unchecked and 1 when checked. I tried it with a hidden field with a 0, but it didn't work because the 0 was always in the POST array. Also when I click the a label, the first foreach label is changing, not the second where I click on. I tried to fix this with a class, but was no success.
Edit:
The foreach is for tasks that exists, but I can also add new items with a piece op JS, they are also inside the form, so I can't give them a foreach-id. I updated my question with the JS example.
Try to set the task id as index of dynamic and check
See below
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[$task->id]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[$task->id]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
#endforeach
--Edit---
if task id is not available then you can set index like below
$index = 0;
#foreach($tasks as $task)
<div class="col-md-9">
<input id="taskfield" name="dynamic[$index]" value="{{ $task->name }}" class="form-control field" type="text">
</div>
<div class="col-md-3">
<div class="slideOne">
<input type="checkbox" value="1" id="slideOne" name="check[$index]" #if($task->finished == 1) checked #endif/>
<label for="slideOne"></label>
</div>
</div>
$index++;
#endforeach
This should do:
#foreach($clubs as $club)
<input type="checkbox"
id="{{$club->getCode()}}"
name="clubs[]"
value="{{$club->getId()}}" /> {{$club->getName()}}<br>
#endforeach