简体   繁体   中英

Array to string conversion laravel 7

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.

If you are trying to retrieve only the list of CUST_CITY with the key CUST_NAME you can use the pluck() method:

$array = DB::table("dummy_db.customer")
    ->take(10)
    ->pluck('CUST_CITY','CUST_NAME');

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 Illuminate\Pagination\LengthAwarePaginator 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]};
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM