Muhammad Abdullah Ali Muhammad Abdullah Ali - 6 months ago 29
PHP Question

Transform() not working Laravel

I am using laravel and i used transform method to change name of the items with in the data object but it is not working it is showing me same data which replicated the database columns name.

<?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());
}
}


and this is the url i am calling:

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

and this is the output i'm getting:

{
"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: i want heading instead of title in the output but not getting it. Transform function not working

Answer

You must pass $lessons to your transform() method.

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