Mustafa Poya
Mustafa Poya

Reputation: 3027

Laravel get specific column name value with passing column name as string to DB result

I want to get the the result of specific column which the name of column is stored in array

I have an array which contain the table name and required column:

$table_info = ['table_name' => 'users', 'column_name' => 'email'];

and I pass the values to DB class query successfully and it work correctly.

$document = DB::table($table_info['table_name'])
            ->select($table_info['column_name'])
            ->where('id', 1)
            ->first();

but when I try to get query result according to $table_info['column_name'] it throws error:

return $document->$table_info['column_name'];

Error:

Array to string conversion

Upvotes: 0

Views: 885

Answers (1)

Anthony Aslangul
Anthony Aslangul

Reputation: 3847

You have to put curly brackets around the dynamic property you want to access to:

return $document->{$table_info['column_name']};

This way, the whole $table_info['column_name'] is read entirely and not only $table_info, which is an array.

Upvotes: 2

Related Questions