i need to get the values without string in array. this will be name of fields :
static function showCust(){ $table = DB::table("dummy_db.customer")->select("*")->paginate(10); $getFieldName = ["CUST_NAME", "CUST_CITY"]; foreach($table as $items){ $a[] = $items->$getFieldName[0]; } dd($a); }
but the results :
ErrorException
Array to string conversion.
Advertisement
Answer
Problem 1: call object property by element of array
The error msg occurs because $getFieldName
as a variable, object call the variable without [0]
, you need to wrap $getFieldName[0]
with brace:
$items->{$getFieldName[0]};
Problem 2: Get collection from paginator:
You are applying paginate
to query-builder, the result will be IlluminatePaginationLengthAwarePaginator
object.
If you want to get the customer objects inside. You can use getCollection()
method to $table
:
foreach($table->getCollection() as $items){ $a[] = $items->${getFieldName[0]}; }