I am using fractal package in laravel 5.3. I have a player model who has hasMany
relationship with videos, so one player has many videos.
Player model:
public function videos()
{
return $this->hasMany(Video::class);
}
Video model:
public function player()
{
return $this->belongsTo(Player::class);
}
I am trying to send player data and include videos data with it. This is the code in the controller:
$player = fractal()
->item($player)
->parseIncludes(['videos'])
->transformWith(new PlayerTransformer)
->toArray();
And this is the PlayerTransformer
:
<?php
namespace App\Transformer;
use App\Player;
class PlayerTransformer extends \League\Fractal\TransformerAbstract
{
protected $availableIncludes = [
'videos'
];
public function transform(Player $player)
{
return [
'id' => $player->id,
'first_name' => $player->first_name,
'last_name' => $player->last_name,
'image' => $player->image_filename,
'club' => $player->club,
'birthday' => $player->birthday,
];
}
public function includeVideos(Player $player)
{
$videos = $player->videos()->where('processed', 1)->get();
return $this->collection($videos, new VideoTransformer);
}
}
I am getting the player data, but I don't get anything for videos. This doesn't work, but what is even weirder if try that with videos, in whose transformer I don't even have includes function:
<?php
namespace App\Transformer;
use App\Video;
class VideoTransformer extends \League\Fractal\TransformerAbstract
{
public function transform(Video $video)
{
return [
'id' => $video->id,
'uid' => $video->uid,
'title' => $video->title,
'image' => $video->getThumbnail(),
'description' => $video->description,
'views' => $video->viewCount(),
'created_at' => $video->created_at->diffForHumans(),
];
}
}
But, when I try to include the player data there, that works:
$videos = fractal()
->collection($videos)
->parseIncludes(['player'])
->transformWith(new VideoTransformer)
->toArray();
I have tried then to apply the same setup I have for the video transformer and remove the $availableIncludes
and includeVideos
in the player transfomer, but it again didn't work there. What am I doing wrong?
I was doing a get without authentication to test my controller and it was giving the error:
PHP Fatal error: Type of App\Transformers\CustomerCategoryTransformer::$availableIncludes must be array (as in class League\Fractal\TransformerAbstract) in /app/Transformers/CustomerCategoryTransformer.php on line 8
I commented out the line:
My code: