我在Laravel 5.2中使用分形。我在这样的集合上使用变压器:
public function allFromCompany()
{
$users = UserModel::all();
return $this->response->collection($users, new UserTransformer);
}
UserTransformer
class UserTransformer extends Fractal\TransformerAbstract
{
public function transform(UserModel $user)
{
return [
'user' => [
'id' => $user->id,
'role' =>
[
'role_id' => $user->role_id,
'name' => $user->role->name
],
'company' =>
[
'company_id' => $user->company_id,
'company' => $user->company->name,
],
'active' => $user->active,
'name' => $user->name,
'lastname' => $user->lastname,
'address' => $user->address,
'zip' => $user->zip,
'email' => $user->email
]
];
}
}
但是,当我这样做时,我收到一个错误:
{
"status_code": 500,
"debug": {
"line": 10,
"file": "/home/vagrant/Code/forum/app/Src/v1/User/UserTransformer.php",
"class": "Symfony\\Component\\Debug\\Exception\\FatalThrowableError",
"trace": [
"#0 /home/vagrant/Code/forum/vendor/league/fractal/src/Scope.php(338): Src\\v1\\User\\UserTransformer->transform(Object(Src\\v1\\User\\User))",
当我尝试使用一个项目时:
return $this->response->item($user, new UserTransformer);
有效。
答案 0 :(得分:0)
这是一个很老的问题,我遇到了:)但如果有人遇到类似的问题,也许您忘记了“使用Helpers”之类的
class UserController extends Controller
{
use Helpers;
public function index()
{
$users = User::all();
return $this->collection($users, new UsersTransformer);
}