Reputation: 625
I created a json field produce_stored
to store array data.
Warehouse Table Structure
In the Warehouse Model I'm using $casts to store the array data
protected $casts = [
'produce_stored' => 'array'
];
In the WarehouseController - index method
$warehouses = DB::table('warehouses')
->join('regions', 'regions.id', '=', 'warehouses.region_id')
->join('districts', 'districts.id', '=', 'warehouses.district_id')
->join('users', 'users.id', '=', 'warehouses.agent_assigned')
->select(
'warehouses.id',
'warehouses.name as warehouseName',
'warehouses.ownership_type',
'warehouses.capacity',
'warehouses.produce_stored', // json field with array data
'regions.name as regionName',
'districts.name as districtName',
'users.name as agent_assigned',
'warehouses.status'
)
->get();
return view('admin.warehouses.index', compact('warehouses'));
In the blade view
{{ $warehouse->produce_stored }}
This is the output in the browser
["1", "2"]
When I try looping through the array to get the produce ids to load the produce names
@foreach ($warehouse->produceStored as $produce)
{{$produce}}
@endforeach
The above throws an error
Invalid argument supplied for foreach()
How do I get the produce ids from the produce_stored field?
Upvotes: 2
Views: 42
Reputation: 12218
you have two choices:
<?php $warehouse->produceStored = json_decode($warehouse->produceStored, false); ?>
and then try
@foreach ($warehouse->produceStored as $produce)
{{$produce}}
@endforeach
2- like Autista_z said in comment:
$warehouses = Warehouse::query()
->join('regions', 'regions.id', '=', 'warehouses.region_id')
->join('districts', 'districts.id', '=', 'warehouses.district_id')
->join('users', 'users.id', '=', 'warehouses.agent_assigned')
->select(
'warehouses.id',
'warehouses.name as warehouseName',
'warehouses.ownership_type',
'warehouses.capacity',
'warehouses.produce_stored', // json field with array data
'regions.name as regionName',
'districts.name as districtName',
'users.name as agent_assigned',
'warehouses.status'
)
->get();
note: replace Warehouse with your model name if they are not the same...
Upvotes: 3