6

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.

4
  • Can you please share your table schema? Commented Oct 10, 2017 at 11:46
  • @sunitiyadav.updated question Commented Oct 10, 2017 at 11:48
  • @vision you want something like a pivot table on category_name? Commented Oct 10, 2017 at 11:57
  • somethink similar as you said without pivot table.i just want to club baes on category .otherwise i have to loop it and create an array. similar to has many Commented Oct 10, 2017 at 11:59

2 Answers 2

4

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'],
        ],
    ]
*/
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.