[Laravel] Transformations

1. update app/controllers/LessonsController.php

public function index()
{
  // 1. All is bad
  // 2. No way to attach meta data
  // 3. Linking db structure to the API output
  // 4. No way to signal headers/response codes
    
  //return Lesson::all();
  
  $lessons = Lesson::all();
  //return Response::json([
    //'data' => $lessons->toArray()
  //], 200);
  return Response::json([
    'data' => $this->transformCollection($lessons);
  ], 200);
}

public function show($id)
{
  $lesson = Lesson::find($id);
  if( ! $lesson)
  {
    return Response::json([
      'error' => [
        'message' => 'Lesson does not exist'
      ]
    ], 404);
  }
    
  return Response::json([
    'data' => $this->transform($lesson->toArray())
  ], 200);
}


public function transformCollection($lessons)
{
  return array_map([$this, 'transform'], $lessons->toArray());
}
  
public function transform($lesson)
{
    return [
        'title' => $lesson['title'],
        'body' => $lesson['body'],
        'active' => (boolean) $lesson['some_bool']
    ];
}