scott
scott

Reputation: 3202

laravel groupby with array

i have post with category

 $response=Post::groupBy('post_category','id')->get();

The above query will return all posts with category in the order of category.

Now i need to group all post inside category. Now i have one possible solution is i need to loop response and inside loop i have to check for category and create array. Is there a option to make it in a query something like groupconcat.?

My question is: Is it possible to create an array of category so key of an array is category_name and inside of category all post?

Updated

Post table

id | post_name | post_description | category_name | etc..

Here category name is not using any other table since its predefined values like news, sports, cricket something like... When i am inserting news, sports, political in categoryname.

Upvotes: 6

Views: 23403

Answers (2)

aaron0207
aaron0207

Reputation: 2333

You can't do it with a query, SQL group by will keep only one post for category so your query is incorrect. What you are looking for is:

$response = Post::get();
$response = $response->groupBy('post_category');

It will return a collection of arrays keyed by 'post_category' and containing all post from this category.

Upvotes: 4

Praveen Tamil
Praveen Tamil

Reputation: 1156

The following code will return the key, value pair of post with unique category_name

$response = Post::get()->groupBy('category_name');
/*
    [
        'category_1' => [
            ['category_name' => 'category_1', 'post_name' => 'Chair'],
            ['category_name' => 'category_1', 'post_name' => 'Bookcase'],
        ],
        'category_2' => [
            ['category_name' => 'category_2', 'post_name' => 'Desk'],
        ],
    ]
*/

Upvotes: 4

Related Questions