Get full value of a query as a Laravel fix?

1

Cordial greetings colleagues, it turns out that I'm doing the following query using query builder in laravel:

public function getSocial_network_post(Post $post)
    {

        $query = DB::table('post_social_networks')->select('social_network_id')->where('post_id','=',$post->id)->get();

        return $query;

    }

From which I receive the following result:

I need to get the whole value of that query and save it in an array so it looks like this:

['1','2']

Any ideas on how I could do this?

    
asked by Kevin Burbano 31.07.2018 в 23:57
source

3 answers

1

Depending on your version of Laravel, you should use pluck or lists .

For Laravel > = 5.2

$query = DB::table('post_social_networks')->where('post_id','=',$post->id)->pluck('social_network_id');

For Laravel < 5.2

$query = DB::table('post_social_networks')->where('post_id','=',$post->id)->lists('social_network_id');

Lists was replaced by pluck in Laravel 5.2

    
answered by 01.08.2018 / 14:09
source
2

What happens is that when calling method ->get() , returns a Collection , the simplest would be to use the function array_column () , but first you must convert to an array that is what that function receives, to convert, you would only do it with - > toArray ()

The code could have this format.

$query = DB::table('post_social_networks')
         ->select('social_network_id')->where('post_id','=',$post->id)->get();

return array_column($query->toArray(), 'social_network_id');
    
answered by 01.08.2018 в 05:36
0

try using the values () function, like this:

$values= $query->values();
return $values->all();

that should return something similar to: [0=>'1',1=>'2']

    
answered by 01.08.2018 в 00:10