I am trying to store my checkbox values in database. I have these three tables.
fields
id name
1 gender
2 looking_for
field_values (here field_id references id on fields table)
id field_id value label
1 1 1 Men
2 1 2 Women
3 2 3 Relationship
4 2 4 Friendship
5 2 5 Marriage
user_interests (here field_id references field_id on field_values table and value_id references value on field_values table)
user_id field_id value_id
1 1 2
1 2 4
1 2 5
gender in blade uses option values and looking_for uses checkbox values. I made one function that is trying to update both of them. I use two foreaches in my function and I am able to successfully update gender option, but I am unable to update looking_for option. When I click submit button nothing happens, also when I dump anything inside that foreach that is supposed to update checkboxes it doesn't dump. Any help is greatly appreciated. Here is my code.
web.php
Route::patch('profile/interests', 'UserProfileController#updateInterestsData')->name('profile.update.interests.data');
UserProfileController.php
public function updateInterestsData(UpdateInterestsDataRequest $request)
{
$user = User::with('userProfile')->where('id', Auth::user()->id)->firstOrFail();
$request->validated();
$userId = $request->input('user_id') ? $request->input('user_id') : Auth::user()->id;
$data = $request->all();
$options = [
'gender' => 1,
'looking_for' => 2
];
foreach ($options as $fieldName => $fieldId) {
if (! empty($data[$fieldName])) {
DB::table('user_interests')
->where('user_id', $userId)
->where('field_id', $fieldId)
->delete();
if (is_array($data[$fieldName])) { // CHECKBOX FIELDS AND HERE IT DOESN'T WORK!!!
//dd('DIE!!!!!!') IT DOESN'T ENTER HERE!!!
foreach ($data[$fieldName] as $key => $value) {
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $value
]);
}
} else { // SELECT FIELDS!!!
DB::table('user_interests')->insert([
'user_id' => $userId,
'field_id' => $fieldId,
'value_id' => $data[$fieldName]
]);
}
}
}
$user->userProfile->update(
[
'age_from_preference' => $request->age_from_preference,
'age_to_preference' => $request->age_to_preference,
'updated_at' => Carbon::now()
]
);
$request->user()->save();
return redirect()->route('profile.show', [$user->username]);
}
index.blade.php
<form action="{{ route('profile.update.interests.data') }}" method="POST" class="flex">
#method('PATCH')
#csrf
<div class="form-group">
<span>Interessiert an</span>
{{-- wrong value - selected --}}
#isset($options)
#foreach($options as $name => $fieldData)
#if ($name == 'gender')
<div class="selectHolder">
<select name="{{ $name }}">
<option selected="true" disabled="disabled" value="" style="display:none">bitte auswählen</option>
#foreach($fieldData['data'] as $value => $label)
<option value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'selected' : '') : '' }}>
{{ $label }}
</option>
#endforeach
</select>
</div>
<?php
unset($options[$name]);
?>
#endif
#endforeach
#endisset
</div>
<div class="form-group">
<span>Im Alter von</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_from_preference ?? "" }}" name="age_from_preference">
<span>Jahren bis</span>
<input type="text" placeholder="XX" maxlength="2" value="{{ $userForShowProfile->userProfile->age_to_preference ?? "" }}" name="age_to_preference">
<span>Jahren</span>
</div>
{{-- wrong value - checked --}}
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name.'-'.$value }}" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }}>
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
<div class="form-group">
<label for="" class="textBold">Button</label>
<input type="submit" class="form-control" name="submit" value="BUTTON">
</div>
</form>
code for $options variable
public static function getProfileLookingForDisplayOptions()
{
$options = [
'gender' => ['id' => 1, 'label' => "Interessiert an"],
'looking_for' => ['id' => 2, 'label' => ""]
];
$data_options = [];
foreach ($options as $field => $value) {
$data_options[$field]['data'] = Value::fieldValues($field);
$data_options[$field]['label'] = $options[$field];
if (!in_array($field, ['gender', 'looking_for'])) {
$data_options[$field]['data'][100] = "Doesn't matter";
}
}
//dd($data_options);
return $data_options;
}
If I understand your problem correctly, to deal with multiple checkboxes on PHP you need to add [] to its name property. That way, PHP knows it should interpret theses values as an array.
Also, your input name is not matching with $data[$fieldName].
Do it like this:
#isset($options)
<div class="form-group flex mt-5">
#foreach($options as $name => $fieldData)
#if ($name == 'looking_for')
#foreach ($options[$name]['data'] as $value=>$label)
<div class="interestedIn">
<input type="checkbox" name="{{ $name }}[]" value="{{ $value }}" {{ isset($data[$fieldData['label']['id']]) ? (in_array($value, $data[$fieldData['label']['id']]) ? 'checked' : null) : '' }} id="{{$name}}-{{ $value }}">
<label for="{{$name}}-{{ $value }}">{{ $label }}</label>
</div>
#endforeach
#endif
#endforeach
</div>
#endisset
Related
To satisfy the requirement (Add support for custom form fields without any plugin or library), I developed a module which allows admin to perform below actions.
Admin can create custom form fields.
Fields data should be encrypted when stored into database.
It can be mapped with multiple countries so if user belongs to that country, selected custom form fields will appear in profile.
Below is my code. Kindly suggest if there are any improvements needed.
Migration file to create custom form fields
public function up()
{
Schema::create('custom_forms', function (Blueprint $table) {
$table->id();
$table->string('title', 250);
$table->string('field_title', 250);
$table->string('field_name', 250);
$table->string('field_input_name', 250);
$table->enum(
'field_type',
[
'text',
'textarea',
'number',
'email',
'date',
'time',
'select',
'radio',
'checkbox',
'tel',
'url'
]
)->default('text');
$table->string('field_min_value', 10)->nullable();
$table->string('field_max_value', 10)->nullable();
$table->text('field_option_values')->nullable();
$table->string('field_validation_pattern', 250)->nullable();
$table->string('field_validation_message', 250)->nullable();
$table->string('field_placeholder', 250)->nullable();
$table->tinyInteger('is_required')->default(0);
$table->integer('country_id');
$table->tinyInteger('is_active')->default(1);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('custom_forms');
}
Migration file to store custom form field values
public function up()
{
Schema::create('custom_form_values', function (Blueprint $table) {
$table->id();
$table->foreignId('form_id')->references('id')->on('custom_forms');
$table->foreignId('user_id')->references('id')->on('users');
$table->mediumText('value')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('custom_form_values');
}
White creating a custom form field, admin can select multiple countries for single. So, I've created a loop for all selected countries and stored the data.
CustomFormController.php
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
foreach ($request->country_id as $country) {
$custom_form = new CustomForm();
$custom_form->title = $request->name;
$custom_form->field_title = $request->name . '-' . Str::random(10);
$custom_form->field_name = $request->field_name;
$custom_form->field_input_name = preg_replace('/\s+/', '', $request->name) . '-' . Str::random(10);
$custom_form->field_type = $request->field_type;
$custom_form->field_min_value = $request->field_min_value;
$custom_form->field_max_value = $request->field_max_value;
$custom_form->field_option_values = $request->field_option_values;
$custom_form->field_validation_pattern = $request->field_validation_pattern;
$custom_form->field_validation_message = $request->field_validation_message;
$custom_form->field_placeholder = $request->field_placeholder;
$custom_form->is_required = $request->field_is_required;
$custom_form->country_id = $country;
$custom_form->save();
}
return redirect()->route('admin.custom-forms.index');
}
In CustomForm.php model, added relation to the values to get data for selected custom form field.
public function values()
{
return $this->belongsTo(CustomFormValue::class, 'id', 'form_id')->select(['id', 'value','form_id']);
}
In CustomFormValue.php model, defined encrypted field to match requirement no. 2.
protected $casts = [
'value' => 'encrypted',
];
Below code is from edit_profile.blade.php to display all custom form fields.
#forelse ($custom_forms as $form)
<div class="form-group">
<label class="required"
for="{{ $form->field_input_name }}">{{ $form->field_name }}</label>
{{-- FOr Text area --}}
#if ($form->field_type === 'textarea')
<textarea class="form-control" type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}" id="{{ $form->field_input_name }}"
minlength="{{ $form->field_min_value }}"
maxlength="{{ $form->field_max_value }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
{{ $form->is_required == 1 ? 'required' : '' }}>{{ $form->values ? $form->values->value : null }}</textarea>
<span class="help-block">{{ $form->field_placeholder }}</span>
{{-- for select option --}}
#elseif ($form->field_type === 'select')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="form-group">
<select class="form-control" type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
{{ $form->is_required == 1 ? 'required' : '' }}>
#forelse ($option_values as $value)
<option #if ($value == $is_selected) selected #endif value="{{ $value }}">
{{ $value }}</option>
#empty
#endforelse
</select>
<span class="help-block">{{ $form->field_placeholder }}</span>
</div>
{{-- for radio buttons --}}
#elseif ($form->field_type === 'radio')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="col-sm-10">
#forelse ($option_values as $value)
<div>
<label>
<input class=" " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $value }}" #if ($value == $is_selected) checked #endif
{{ $form->is_required == 1 ? 'required' : '' }}>{{ $value }}
</label>
</div>
#empty
#endforelse
</div>
{{-- for checkbox --}}
#elseif ($form->field_type === 'checkbox')
#php
$option_values = explode(',', $form->field_option_values);
$is_selected = $form->values ? $form->values->value : '';
#endphp
<div class="col-sm-10">
#forelse ($option_values as $value)
<div>
<label>
<input class=" " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}[]"
id="{{ $form->field_input_name }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $value }}" #if (str_contains($is_selected,$value)) checked #endif
>{{ $value }}
</label>
</div>
#empty
#endforelse
</div>
#else
<input class="form-control " type="{{ $form->field_type }}"
name="custom_form_{{ $form->id }}" id="{{ $form->field_input_name }}"
minlength="{{ $form->field_min_value }}"
maxlength="{{ $form->field_max_value }}" {{-- pattern="{{ $form->field_validation_pattern }}" --}}
title="{{ $form->field_validation_message }}"
placeholder="{{ $form->field_placeholder }}"
value="{{ $form->values ? $form->values->value : null }}"
#if($form->field_validation_pattern) pattern="{{ $form->field_validation_pattern }}" #endif
{{ $form->is_required == 1 ? 'required' : '' }}>
<span class="help-block">{{ $form->field_placeholder }}</span>
#endif
</div>
#empty
{{-- Message to display if there is no custom field added--}}
#endforelse
To store user entered custom form field values, in UserController.php
foreach ($custom_values as $key => $value) {
$form_value = Str::contains($key, 'custom_form_');
if ($form_value == 1) {
$form_id = str_replace('custom_form_', '', $key);
$custom_form_value = CustomFormValue::updateOrCreate([
'form_id' => $form_id,
'user_id' => Auth::user()->id
], [
'form_id' => $form_id,
'user_id' => Auth::user()->id,
'value' => is_array($value) ? implode(', ', $value) : $value
]);
}
}
One user can have many custom form field values. So, in User.php model,
public function customFormValue()
{
return $this->hasMany(CustomFormValue::class, 'user_id');
}
And finally, to display custom form values, in profile.blade.php
#forelse ($custom_forms as $form)
<tr>
<td>
{{ $form->field_name }}: <strong class="pull-right">{{ $form->values ? $form->values->value : '' }}</strong>
</td>
</tr>
#empty
{{-- Message if any --}}
#endforelse
So, this is what I have done so far to add support for custom form field without any plugin or library. Let me know if there is any room for improvement.
I hope it may help others who are looking for something similar.
Here are some points that you can implement for a better scalable system.
1) custom_forms table
We can store the nullable fields in JSON. So we can avoid the multiple nullable fields because it can be possible to have 50% nullable values. It is effective for storage purposes and will make a more efficient and scalable DB design.
2) custom_form_values table
$table->mediumText('value')->nullable() TO $table->json('value')->nullable()
NOTE - The JSON column type is recommended as it allows you to do SQL queries on JSON data. Here is a quick doc link https://dev.mysql.com/doc/refman/8.0/en/json.html
3) CustomFormController.php
Here we can do the bulk insertion. So the query will not fire every time. Reference - https://stackoverflow.com/a/29723968/7796116
4) edit_profile.blade.php
AVOID USING MULTIPLE IF/ELSE. IT WILL CREATES ISSUES AT TIME OF SCALIBILITY. Use components instead so it will make code more readable and scalable.
Here is the laravel components doc https://laravel.com/docs/9.x/blade#components
5) General Tips
Try to use the Null Coalescing operator instead ternary.
Hope this will help you.
How can I add a property type array in Laravel livewire,
Here is blade file :
#foreach (config('translatable.locales') as $locale => $key)
<div class="col-md-6">
<div class="form-group">
<label> {{ trans('site.' . $key . '.service_title') }} </label>
<input type="text" wire:model="{{ $key }}[service_title]"
class="form-control {{ $errors->has($key . '.service_title') ? 'is-invalid' : '' }} "
name="{{ $key }}[service_title]"
placeholder="{{ trans('site.' . $key . '.service_title') }}">
</div>
</div>
#endforeach
Component :
public $ar = ['service_title' , 'service_description'];
public $en = ['service_title' , 'service_description'];
public function store(ServiceRequest $request)
{
$data = $this->validate($request->rules);
Service::create($data);
session()->flash('success', trans('site.msg_added_successfully'));
}
}
The error when I write on service title input
Thanks
I have a checkbox field in my form, I want to insert data to database if the checkbox is checked and delete the data in database if the checkbox is unchecked.
Here is my checkbox code:
<ul class="list-unstyled mb-0">
#foreach ($companies as $company)
<li class="d-inline-block mr-2 mb-1">
<fieldset>
<div class="checkbox">
<input type="checkbox" name="company_id[]"
class="checkbox-input" value="{{ $company->id }}"
id="{{ $company->id }}"
#foreach ($supervisor_company as $spv)
#if ($spv != null)
#if ($spv->company_id == $company->id)
checked
#endif
#endif
#endforeach>
<label for="{{ $company->id }}">{{ $company->name }}</label>
</div>
</fieldset>
</li>
<li class="d-inline-block mr-2 mb-1">
#endforeach
</ul>
And this is my controller:
if ($request->has('company_id')) {
foreach ($request->company_id as $key => $company) {
$spv_data = EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->first();
if ($spv_data != null) {
EmployeeSpvCompany::where('employee_id', $employee_id)->where('company_id', $company)->update(['company_id' => $company]);
} else {
$emp_spv = new EmployeeSpvCompany;
$emp_spv->employee_id = $employee_id;
$emp_spv->company_id = $company;
$emp_spv->save();
}
}
}
Insert to database if the checkbox is checked is already working, but I don't know how to delete the data in database if the checkbox is unchecked
I expect the company_id field is a multi-select type so the value will be returned in the form of an array. I guess the following code will work in this situation.
$companyIds = $request->has('company_id'); // [1, 2]
if ($companyIds) {
foreach ($companyIds as $company_id) {
$employeeSpvCompanyInstance = EmployeeSpvCompany::firstOrCreate([
'employee_id' => $employee_id,
'company_id' => $company_id
]);
}
EmployeeSpvCompany::where('employee_id', $employee_id)->whereNotIn('company_id', $companyIds)->delete();
} else {
EmployeeSpvCompany::where('employee_id', $employee_id)->delete();
}
Ah!! I found something called whereNotIn. I just need to check if the data is not in my array request.
EmployeeSpvCompany::whereNotIn('company_id', $request->company_id)->delete();
I have input group include 2 options checkbox and input field.
I want to get value of input field only if checkbox is checked
otherwise ignore that input field.
Codes
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
currently I get all my inputs in my controller regardless they are checked or not:
$column = $request->except('_token');
How do I pass this to my controller function?
UPDATE
as requested : my code $list dd is:
array:27 [▼
0 => "id"
1 => "title"
2 => "slug"
3 => "imageOne"
4 => "imageTwo"
5 => "short_description"
6 => "description"
7 => "price"
8 => "meta_description"
9 => "meta_tags"
10 => "arrivalDays"
11 => "height"
12 => "weight"
13 => "lenght"
14 => "width"
15 => "sku"
16 => "stock"
17 => "label"
18 => "label_from"
19 => "label_to"
20 => "label_color"
21 => "status_id"
22 => "brand_id"
23 => "category_id"
24 => "subcategory_id"
25 => "created_at"
26 => "updated_at"
]
UPDATE 2
To be clear how it works exactly i included screenshot
SEE IT
1) change the name of checkbox to cb[] and input to input[]
#php
$no = 0;
#endphp
#foreach($list as $columns)
#php
$no+=1;
#endphp
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked">
</span>
<input type="text" name="input[{{$no}}]" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2)filter your $request and include just the checked checkbox
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['input'][$key];
}
}
return $getRealInput;
Try This:
1) first of all mention checkbox name like this :
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="checkbox" type="checkbox" checked="checked">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
2) In Controller try this:
$inputs = asset($request->checkbox) && $request->checkbox !='' ? $request->except('_token') : []; //if you want to remove input fields use unset inputs instead of []
dd($inputs)
You could name the checkbox as an array
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
and in your controller you could get the checked items as
foreach ($request->cb as $checked) {
$request->{$checked} // The textbox corresponding to the selected checkbox
}
You should try this:
Updated Answer:
#foreach($list as $columns)
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="columns[]" value="{{ $columns }}">
</span>
<input type="text" name="{{$columns}}" value="{{$columns}}" class="form-control">
</div><!-- /input-group -->
#endforeach
In controller :
$columns = $request->columns;
print_r($columns);
First of all, identify each checkboxes with unique names(use columns[]).
Here I guess you don't expect manual entry(modification) as you populate the value of $columns in your text input field. If so, yoou could use a label instead:
#foreach($list as $key => $columns)
<div class="input-group">
<span class="input-group-addon">
<input name="columns[]" type="checkbox" value={{$key}} checked="checked">
</span>
<label class="form-control">{{$columns}}</label>
</div>
#endforeach
UPDATE:
VIEW
#foreach($list as $key => $columns)
<span class="input-group-addon">
<input name="col_keys[]" type="checkbox" value={{$key}} checked="checked">
</span>
<input type="text" name="col_texts[]" value="{{$columns}}" class="form-control">
#endforeach
CONTROLLER
Now $request->col_keys will have an array of keys that are valid for $request->col_texts. So do a sorting:
$valid_keys = $request->col_keys;
$all_texts = $reqest->col_texts;
foreach($all_texts as $key => $item) {
if (($key = array_search($key, $valid_keys)) === false) {
unset($all_texts($key));
}
}
SOLVED
First of all I have to thank everyone who tried to help me solve this issue specially Wahyu Fadzar. Here is how I solved my issue:
I changed my blade code to:
#php $no = 0; #endphp //Wahyu Fadzar idea
#foreach($list as $columns)
#php $no+=1; #endphp //Wahyu Fadzar idea
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cb[{{$no}}]" checked="checked"> //Wahyu Fadzar idea
</span>
<input type="text" name="customname[{{$no}}]" value="{{$columns}}" //Wahyu Fadzar ideaclass="form-control">
<input type="hidden" name="defaultname[{{$no}}]" value="{{$columns}}"> // Added
</div><!-- /input-group -->
#endforeach
Controller
public function export(Request $request) {
// defaultname that i added in my blade used here (explaination below)
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getRealInput[$key] = $input['defaultname'][$key];
}
}
$products = Product::select($getRealInput)->get(); //getting table selected columns
Excel::create('products', function($excel) use($products, $request) {
$excel->sheet('sheet 1', function($sheet) use($products, $request){
//Wahyu Fadzar code used here to get selected columns data
$input = $request->except('_token');
foreach ($input['cb'] as $key => $value) {
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
}
$sheet->fromArray($products, null, 'A1', false, false);
$sheet->row(1, $getCustomInput);
});
})->export('csv');
return redirect()->back();
}
Explanations
I had issue before when I used Wahyu code it would remove my inputs from CSV file as i unchecked them, but their data still exist in my file
so I added
< input type = " hidden " name = " defaultname[{{$no}}] " value = " {{$columns}} " >
and by this i will get my default column names even if i edit it for export. otherwise it would return error, eg. I changed my title column to name it says there is no column name! so by this my title column will stay title for select query.
I used it in:
$products = Product::select($getRealInput)->get();
I used Wahyu code in my export part in order to get custom input names for my CSV file and not the default ones.
< input type = " text " name = " customname[{{$no}}] " value = "
{{$columns}} " class = " form-control " >
goes to:
if ($value== 'on') {
$getCustomInput[$key] = $input['customname'][$key];
}
inside my export query.
Hope it help others as well.
THANK YOU ALL.
I have a bit of a problem what i am stuck with.
I have a ManyToMany relation storing body measurements in my database and these are serialized arrays,
My measurements table
id | name | value
1 | Height | a:61:{i:0;s:6:"150 cm";i:1;s:6:"151 cm";i:2;s:6:"152 cm";i:3;s:6:"153 cm";i:4;s:6:"154 cm";i:5;s:6:"155 cm";i:6;s:6:"156 cm";i:7;s:6:"157 cm";i:8;s:6:"158 cm";i:9;s:6:"159 cm";i:10;s:6:"160 cm";i:11;s:6:"161 cm";i:12;s:6:"162 cm";i:13;s:6:"163 cm";i:14;s:6:"164 cm";i:15;s:6:"165 cm";i:16;s:6:"166 cm";i:17;s:6:"167 cm";i:18;s:6:"168 cm";i:19;s:6:"169 cm";i:20;s:6:"170 cm";i:21;s:6:"171 cm";i:22;s:6:"172 cm";i:23;s:6:"173 cm";i:24;s:6:"174 cm";i:25;s:6:"175 cm";i:26;s:6:"176 cm";i:27;s:6:"177 cm";i:28;s:6:"178 cm";i:29;s:6:"179 cm";i:30;s:6:"180 cm";i:31;s:6:"181 cm";i:32;s:6:"182 cm";i:33;s:6:"183 cm";i:34;s:6:"184 cm";i:35;s:6:"185 cm";i:36;s:6:"186 cm";i:37;s:6:"187 cm";i:38;s:6:"188 cm";i:39;s:6:"189 cm";i:40;s:6:"190 cm";i:41;s:6:"191 cm";i:42;s:6:"192 cm";i:43;s:6:"193 cm";i:44;s:6:"194 cm";i:45;s:6:"195 cm";i:46;s:6:"196 cm";i:47;s:6:"197 cm";i:48;s:6:"198 cm";i:49;s:6:"199 cm";i:50;s:6:"200 cm";i:51;s:6:"201 cm";i:52;s:6:"202 cm";i:53;s:6:"203 cm";i:54;s:6:"204 cm";i:55;s:6:"205 cm";i:56;s:6:"206 cm";i:57;s:6:"207 cm";i:58;s:6:"208 cm";i:59;s:6:"209 cm";i:60;s:6:"210 cm";}
2 | Weight | a:76:{i:0;s:5:"35 kg";i:1;s:5:"36 kg";i:2;s:5:"37 kg";i:3;s:5:"38 kg";i:4;s:5:"39 kg";i:5;s:5:"40 kg";i:6;s:5:"41 kg";i:7;s:5:"42 kg";i:8;s:5:"43 kg";i:9;s:5:"44 kg";i:10;s:5:"45 kg";i:11;s:5:"46 kg";i:12;s:5:"47 kg";i:13;s:5:"48 kg";i:14;s:5:"49 kg";i:15;s:5:"50 kg";i:16;s:5:"51 kg";i:17;s:5:"52 kg";i:18;s:5:"53 kg";i:19;s:5:"54 kg";i:20;s:5:"55 kg";i:21;s:5:"56 kg";i:22;s:5:"57 kg";i:23;s:5:"58 kg";i:24;s:5:"59 kg";i:25;s:5:"60 kg";i:26;s:5:"61 kg";i:27;s:5:"62 kg";i:28;s:5:"63 kg";i:29;s:5:"64 kg";i:30;s:5:"65 kg";i:31;s:5:"66 kg";i:32;s:5:"67 kg";i:33;s:5:"68 kg";i:34;s:5:"69 kg";i:35;s:5:"70 kg";i:36;s:5:"71 kg";i:37;s:5:"72 kg";i:38;s:5:"73 kg";i:39;s:5:"74 kg";i:40;s:5:"75 kg";i:41;s:5:"76 kg";i:42;s:5:"77 kg";i:43;s:5:"78 kg";i:44;s:5:"79 kg";i:45;s:5:"80 kg";i:46;s:5:"81 kg";i:47;s:5:"82 kg";i:48;s:5:"83 kg";i:49;s:5:"84 kg";i:50;s:5:"85 kg";i:51;s:5:"86 kg";i:52;s:5:"87 kg";i:53;s:5:"88 kg";i:54;s:5:"89 kg";i:55;s:5:"90 kg";i:56;s:5:"91 kg";i:57;s:5:"92 kg";i:58;s:5:"93 kg";i:59;s:5:"94 kg";i:60;s:5:"95 kg";i:61;s:5:"96 kg";i:62;s:5:"97 kg";i:63;s:5:"98 kg";i:64;s:5:"99 kg";i:65;s:6:"100 kg";i:66;s:6:"101 kg";i:67;s:6:"102 kg";i:68;s:6:"103 kg";i:69;s:6:"104 kg";i:70;s:6:"105 kg";i:71;s:6:"106 kg";i:72;s:6:"107 kg";i:73;s:6:"108 kg";i:74;s:6:"109 kg";i:75;s:6:"110 kg";}
Relation table users_measurements
user_id | measurement_id | value
1 | 1 | 160 cm
1 | 2 | 50 kg
measurements controller
public function measurements()
{
$user = Auth::user();
$measurements = Measurement::all();
$this->layout->title = "Measurements";
$this->layout->content = View::make('user::settings/measurements')
->with('user', $user)
->with('measurements', $measurements);
}
And my view, i loop through the results to generate a form
View
{{ Form::open(array('id' => 'ajax-', 'class' => 'ui fluid form segment')) }}
<div class="two fields">
#foreach($measurements as $measurement)
<div class="field">
<label for="{{ $measurement->id }}">{{ $measurement->name }}</label>
<select name="{{ $measurement->id }}" id="{{ $measurement->id }}" class="form-select">
<option value="">{{ $measurement->name }} kiválasztása</option>
#foreach(unserialize($measurement->value) as $value)
<option value="{{ $value }}" >{{ $value }}</option>
#endforeach
</select>
</div>
#endforeach
</div>
{{ Form::submit('Módosítások mentése', array('class' => 'ui tiny orange button')) }}
{{ Form::close() }}
So i am really stuck how to solve to add the actual selected attribute to my selectbox
I tried a few things.
In my controller i store the logged in user in the $user variable.
I tried
$user-measurement->lists('value');
This gave back the following result
array(2) { [0]=> string(1095) "a:61:{i:0;s:6:"150 cm";i:1;s:6:"151 cm";i:2;s:6:"152 cm";i:3;s:6:"153 cm";i:4;s:6:"154 cm";i:5;s:6:"155 cm";i:6;s:6:"156 cm";i:7;s:6:"157 cm";i:8;s:6:"158 cm";i:9;s:6:"159 cm";i:10;s:6:"160 cm";i:11;s:6:"161 cm";i:12;s:6:"162 cm";i:13;s:6:"163 cm";i:14;s:6:"164 cm";i:15;s:6:"165 cm";i:16;s:6:"166 cm";i:17;s:6:"167 cm";i:18;s:6:"168 cm";i:19;s:6:"169 cm";i:20;s:6:"170 cm";i:21;s:6:"171 cm";i:22;s:6:"172 cm";i:23;s:6:"173 cm";i:24;s:6:"174 cm";i:25;s:6:"175 cm";i:26;s:6:"176 cm";i:27;s:6:"177 cm";i:28;s:6:"178 cm";i:29;s:6:"179 cm";i:30;s:6:"180 cm";i:31;s:6:"181 cm";i:32;s:6:"182 cm";i:33;s:6:"183 cm";i:34;s:6:"184 cm";i:35;s:6:"185 cm";i:36;s:6:"186 cm";i:37;s:6:"187 cm";i:38;s:6:"188 cm";i:39;s:6:"189 cm";i:40;s:6:"190 cm";i:41;s:6:"191 cm";i:42;s:6:"192 cm";i:43;s:6:"193 cm";i:44;s:6:"194 cm";i:45;s:6:"195 cm";i:46;s:6:"196 cm";i:47;s:6:"197 cm";i:48;s:6:"198 cm";i:49;s:6:"199 cm";i:50;s:6:"200 cm";i:51;s:6:"201 cm";i:52;s:6:"202 cm";i:53;s:6:"203 cm";i:54;s:6:"204 cm";i:55;s:6:"205 cm";i:56;s:6:"206 cm";i:57;s:6:"207 cm";i:58;s:6:"208 cm";i:59;s:6:"209 cm";i:60;s:6:"210 cm";}" [1]=> string(1300) "a:76:{i:0;s:5:"35 kg";i:1;s:5:"36 kg";i:2;s:5:"37 kg";i:3;s:5:"38 kg";i:4;s:5:"39 kg";i:5;s:5:"40 kg";i:6;s:5:"41 kg";i:7;s:5:"42 kg";i:8;s:5:"43 kg";i:9;s:5:"44 kg";i:10;s:5:"45 kg";i:11;s:5:"46 kg";i:12;s:5:"47 kg";i:13;s:5:"48 kg";i:14;s:5:"49 kg";i:15;s:5:"50 kg";i:16;s:5:"51 kg";i:17;s:5:"52 kg";i:18;s:5:"53 kg";i:19;s:5:"54 kg";i:20;s:5:"55 kg";i:21;s:5:"56 kg";i:22;s:5:"57 kg";i:23;s:5:"58 kg";i:24;s:5:"59 kg";i:25;s:5:"60 kg";i:26;s:5:"61 kg";i:27;s:5:"62 kg";i:28;s:5:"63 kg";i:29;s:5:"64 kg";i:30;s:5:"65 kg";i:31;s:5:"66 kg";i:32;s:5:"67 kg";i:33;s:5:"68 kg";i:34;s:5:"69 kg";i:35;s:5:"70 kg";i:36;s:5:"71 kg";i:37;s:5:"72 kg";i:38;s:5:"73 kg";i:39;s:5:"74 kg";i:40;s:5:"75 kg";i:41;s:5:"76 kg";i:42;s:5:"77 kg";i:43;s:5:"78 kg";i:44;s:5:"79 kg";i:45;s:5:"80 kg";i:46;s:5:"81 kg";i:47;s:5:"82 kg";i:48;s:5:"83 kg";i:49;s:5:"84 kg";i:50;s:5:"85 kg";i:51;s:5:"86 kg";i:52;s:5:"87 kg";i:53;s:5:"88 kg";i:54;s:5:"89 kg";i:55;s:5:"90 kg";i:56;s:5:"91 kg";i:57;s:5:"92 kg";i:58;s:5:"93 kg";i:59;s:5:"94 kg";i:60;s:5:"95 kg";i:61;s:5:"96 kg";i:62;s:5:"97 kg";i:63;s:5:"98 kg";i:64;s:5:"99 kg";i:65;s:6:"100 kg";i:66;s:6:"101 kg";i:67;s:6:"102 kg";i:68;s:6:"103 kg";i:69;s:6:"104 kg";i:70;s:6:"105 kg";i:71;s:6:"106 kg";i:72;s:6:"107 kg";i:73;s:6:"108 kg";i:74;s:6:"109 kg";i:75;s:6:"110 kg";}" }
I tried so many methods to process this data to return the actual users pivot column values, but no luck
If anybody could help me out would really make my day, or any hint please
Thank you
{{ Form::select($measurement->id, unserialize($measurement->value), $user->value, array("id" => $measurement->id, "class" => "form-select") ) }}
Try this.
Okay if anybody else needs help with this i wrote a function in my user model
public function selectedMeasurement()
{
foreach ($this->measurement as $measurement)
{
$selected[] = $measurement->pivot->value;
}
if (!empty($selected))
{
return $selected;
}
else
{
return array();
}
}
And in my view
{{ Form::open(array('id' => 'ajax-', 'class' => 'ui fluid form segment')) }}
<div class="two fields">
#foreach($measurements as $measurement)
<div class="field">
<label for="{{ $measurement->id }}">{{ $measurement->name }}</label>
<select name="{{ $measurement->id }}" id="{{ $measurement->id }}" class="form-select">
<option value="">{{ $measurement->name }} kiválasztása</option>
#foreach(unserialize($measurement->value) as $value)
<option value="{{ $value }}" {{ in_array($value, $user->selectedMeasurement()) ? 'selected="selected"' : "" }} >{{ $value }}</option>
#endforeach
</select>
</div>
#endforeach
</div>
{{ Form::submit('Módosítások mentése', array('class' => 'ui tiny orange button')) }}
{{ Form::close() }}
I had the same problem and that is how I solved it.
I added this in my controller, in the edit method and passed it into the view:
$selectedTags = $product->tags()->pluck('tag_id')->toArray();
And in the view file I added it like this:
<option value="{{$row->id}}"{!! in_array($row->id, $selectedTags) ? ' selected="selected"' : '' !!}>{{$row->name}}</option>