Reputation: 87
I have to following array from inputs
array:9 [
"columns" => "4"
"device_id" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
"hub_id" => "11"
"usage" => array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
....
In my foreach loop i get back only one value not all
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will return only 1 one value not all.
I have problem displaying all the value and saving them to database. Witch would be the fast and the right way ?
Upvotes: 1
Views: 1008
Reputation: 3570
You do not save array in a database. Databases are not supposed to save multidimensional structures, since they do not support them.
You must convert your array into a format that the database is able to save, for example JSON or PHP serialize. It is actually very common to save data in this way if you do not need to search it easily at a later time.
Nevertheless, I would use a setter in your model to achieve this:
public function setAttributeNameAttribute($values)
{
$this->attributes['attribute_name'] = json_encode($values);
}
public function getAttributeNameAttribute($values)
{
return json_decode($values);
}
Upvotes: 1
Reputation: 3857
The array and the behaviour you are getting is normal.
$devices = $request->all();
foreach ($devices["device_id"] as $device) {
dd($device);
}
This will indeed return 1
, because your cursor is at the first value of $devices["device_id"]
. If you wait for the next iteration, it'll be 2
, then 3
and 4
.
Remember you can also write your foreach this way:
foreach ($devices["device_id"] as $index => $device)
, where $index
will be equal to the index related to the current value.
If you want all values, you can just simply dd($devices["device_id"])
, it'll return you this array:
array:4 [
0 => "1"
1 => "2"
2 => "3"
3 => "4"
]
Upvotes: 1