Attach result of for loop to eloquent output in Laravel

  arrays, eloquent, laravel, loops, php

Good day. Like I explained in this post Using Query Builder and MySql to get categories and sub – categories, I want to make something meaningful from this table. I decided to go the Eloquent way. I am able to get the distinct categories as shown below. How do i loop through each title belonging to a a particular category?
For example, get it in the form:


Title 1
Title 5


Title 2
Title 3
Title 4

My code is shown below

public function type(Request $request){
    $details = [];

    $categories = Category::distinct()->get(['category']); //Get the distinct categories from the category column in the table

    foreach($categories as $category){
      $titles = Category::where('type',$category->type);
      $details = ['cat'=>$category->type,[
          'title' => $titles->title,
          'pk' => $titles->pk

    return response()->json([
         "Data" => $details

Not getting a result. Is there a better way this can be done please?

Source: Ask PHP