John Davidson

php - dynamically assign a part of variable name in laravel 8 controller

0 comments
Message:


I have an array with some measurement values that corresponds to different sensors.
These measurements should be stored in my Measurements table.
But I cannot form the variable name dynamically. => ${'request->AI' . '$counter'};


Any suggestions?


$this->validateWith([
'RecorderName' => 'required|string',
'Time' => 'required|date',
'AI1' => 'required|float',
'AI2' => 'required|float',
'AI3' => 'required|float',
'AI4' => 'required|float',
'AI5' => 'required|float',
'AI6' => 'required|float']);

$recorderSenor = Recorder::where('name', substr($request->RecorderName, 0, -4))->with('getSensorsRelation')->get();

$counter =1;

foreach ($recorderSenor as $sensor) {
$measurement = new measurement();
$measurement->sensor_id = $sensor->id;
$measurement->value = ${'request->AI' . '$counter'};
$measurement->timestamp = $request->time;
$measurement->save();
$counter++;
}


My Answer:
You can use the `input()` method of the Request object to dynamically access the values of the AI fields in your controller. Here's how you can modify your code to achieve this:

php
$this->validateWith([
'RecorderName' => 'required|string',
'Time' => 'required|date',
'AI1' => 'required|float',
'AI2' => 'required|float',
'AI3' => 'required|float',
'AI4' => 'required|float',
'AI5' => 'required|float',
'AI6' => 'required|float'
]);

$recorderSenor = Recorder::where('name', substr($request->RecorderName, 0, -4))->with('getSensorsRelation')->get();

$counter = 1;

foreach ($recorderSenor as $sensor) {
$measurement = new Measurement();
$measurement->sensor_id = $sensor->id;
$measurement->value = $request->input('AI' . $counter);
$measurement->timestamp = $request->Time;
$measurement->save();
$counter++;
}


In this code snippet, we are using the `input()` method of the `$request` object to dynamically access the values of the AI fields by concatenating the field name with the current counter value. This way, you can access the values of the AI fields without having to dynamically construct variable names.

Rate this post

4 of 5 based on 8162 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us