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>
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.
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
I'm new in Laravel and it is my first question.
I have 3 tables:
categories: id, name (at the moment 2 items)
variants: id, name
category_variant: id, category_id, variant_id; <--
Every variant has 1 or 2 categories
In the VariantController I have following code:
public function edit($id)
{
$variant = Variant::where('id', $id)->with('categories')->first();
$categories = Category::all();
return view('admin.variant.edit', compact('variant', 'categories'));
}
In the edit.blade.php I have following html:
#foreach ($categories as $key=>$category)
<div class="form-group form-float">
#if (isset($variant->categories[$key]->pivot->category_id)) <-- I think here is the problem
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" {{ $category->id == $variant->categories[$key]->pivot->category_id ? 'checked' : ''}} >
<label for="wb">{{ $category->name}}</label>
#else
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}">
<label for="wb">{{ $category->name}}</label>
#endif
</div>
#endforeach
I want to know which category was checked in the checkbox. If the variant has all 2 categories everthing is ok but if the user has chosen only one category I get an error
Undefined offset: 1 (View: /shui/resources/views/admin/variant/edit.blade.php)
How can I solve this problem?
Thanks in advance
Dimi
You can use the power of collection:
#if($variant->categories->contains($category))
{{-- You does not need to test a second time to know if you need to "check" --}}
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" checked >
<label for="wb">{{ $category->name}}</label>
#else
{{-- Do stuff --}}
#endif
Or simpler. Remove the first #if
<input type="checkbox" id="wb" class="filled-in" name="wb" value="{{$category->id}}" $variant->categories->contains($category)? 'checked' : '' >
<label for="wb">{{ $category->name}}</label>
Also in you Controller, you can simplify
$variant = Variant::where('id', $id)->with('categories')->first();
with
$variant = Variant::with('categories')->find($id);
// Or better, Laravel throws a 404 error when the id doesn't exists
$variant = Variant::with('categories')->findOrFail($id);
I have the following controller, which sends data to a Laravel Blade view:
Controller:
public function create()
{
$schools = School::all()->sortBy('school_type');
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
}
In that Laravel blade view there is a form:
<form method="GET" action="{{ route('invoices.choose-periods') }}">
<div class="form-group {{ $errors->has('school') ? 'has-error' : '' }}">
<label>School</label>
<select id="school" class="form-control" name="school[]" multiple size="{{ $schools->count() }}" required>
#foreach ($schools as $school)
<option value="{{ $school->id }}">{{ $school->name }}</option>
#endforeach
</select>
#if ($errors->has('school'))
<span class="help-block">
<strong>{{ $errors->first('school') }}</strong>
</span>
#endif
</div>
<button type="submit" class="btn btn-success btn-sm pull-right">Submit</button>
</form>
As you can see from the HTML, the form is a multi-select form, with the resulting data stored in a school[] array.
On submission of the form, I do a test die and dump on request('school') and see that for every option I have selected, the value seems to have been logged twice. For example, choosing only one option gives me:
array:2 [▼
0 => "15"
1 => "15"
]
Any ideas? Thanks!
I have only worked on laravel 5.7. Try this It is working for me.
Since you are passing 2 objects
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
It is obvious you will get 2 errors.
In your controller change this
public function create()
{
$schools = School::all()->sortBy('school_type');
return view('invoices.create')->with([
'schools' => $schools,
'dayTypes' => $dayTypes,
]);
}
to this
public function create(){
$schools = School::all()->sortBy('school_type');
return view('invoices.create', ['schools' => $schools]),
]);
}
I have a form that asks the user to make 10 game picks and then sort the picks based on confidence. I'm using jQuery's sortable function and then populating a hidden form element (order-array) with a serialized string on each update to the order. My problem is how to deal with this array of serialized data in my controller after submission so I can store it (plus the actual game picks) into my database.
My Form View
{{ Form::open() }}
<h1>Games for Week {{ $weeknum }} </h1>
<h3>Visitors # Hometeam</h3>
<input type="hidden" name="order-array" id="order-array" value="">
<ul id="gamelist">
<?php $count = 1; ?>
#foreach($games as $game)
<li class="game-rank" id="c_{{ $count }}">
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->visitor }}">
{{ $game->visitor }} #
<input type="radio" name="{{ "pick_".$game->id }}" value="{{ $game->hometeam }}">
{{ $game->hometeam }}
<input type="hidden" name="{{ "game_".$count }}" value="{{ $game->id }}">
</li>
<?php $count++; ?>
#endforeach
</ul>
#if(Auth::check())
{{ Form::hidden('player', $player) }}
{{ Form::submit('Submit Picks', array('class' => 'link-button')) }}
#endif
{{ Form::close() }}
The serialized confidence data being passed to the controller
"c[]=1&c[]=3&c[]=9&c[]=4&c[]=5&c[]=6&c[]=2&c[]=7&c[]=8&c[]=10"
My controller function
public function post_new()
{
$confidence = Input::get('order-array');
for ($i=1;$i<=10;$i++) {
$array_index = $i-1;
$pick = new Pick;
$pick->user_id = Input::get('player');
$pick->game_id = Input::get("game_$i"); // game number
$pick->pick = Input::get("pick_$i"); // teamname
$pick->confidence = $confidence[$array_index];
$pick->save();
}
return Redirect::to ('users');
}
Everything works except for the confidence data. What adjustments do I need to make to my controller?
Thanks!!