变换()不起作用Laravel

时间:2016-06-09 05:28:20

标签: php laravel

我正在使用laravel,我使用transform方法在数据对象中更改项目的名称,但它不起作用,它显示了复制数据库列名称的相同数据。

<?php
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Lessons;
    use Illuminate\Support\Facades\Response;
    use League\Fractal\TransformerAbstract;
    class LessonsController extends Controller
    {
        public function index()
        {
            $lessons= Lessons::all();
            return Response::json([
                'data'=>$lessons->toArray()
            ],200);
        }

        public function show($id)
        {
        $lessons= Lessons::find($id);
        if(! $lessons)
        {
            return Response::json([    
                'error'=>[
                    'message'=>'Lesson not found',
                ]
            ],404); 
        }
        return Response::json([
            'data'=>$lessons->toArray()
        ],200);
    }
    private function transform ($lessons)
    {
        return array_map(function($lesson)
        {
            return [
                'heading'=>$lesson['title'],
                'body'=>$lesson['body']
            ];
        },$lessons->toArray());
    }
}

这是我打电话的网址:

http://localhost:8000/api/v1/lessons

这是我得到的输出:

  {
  "data": [
    {
      "title": "Title 1",
      "body": "body 1"
    },
    {
      "title": "title 2",
      "body": "body 2"
    },
    {
      "title": "Title 3",
      "body": "body 3"
    },
    {
      "title": "title 4",
      "body": "body 4"
    }
  ]
}

Bottomline:我想在输出中使用标题而不是标题,但是没有得到它。转换功能不起作用

1 个答案:

答案 0 :(得分:0)

您必须将$lessons传递给transform()方法。

public function index()
{
    $lessons= Lessons::all();
    return Response::json([
        'data'=> $this->transform($lessons)
    ], 200);
}