How to call laravel JsonResource whenLoaded method in another class?
Hi. please somebody help me with this. My application support users with roles. So each user can have a single role.I am using UserResource and it's collection class to get users from server. I would like to get different columns of users table based on user role. So I am using sort of strategy pattern and delegating resource object from it's class to the resource class of specific object. Please see below:
<?php
namespace App\Utils\Resources;
abstract class Resource {
public abstract function get_items($resource);
}
<?php
namespace App\Utils\Resources\Users;
use App\Utils\Resources\Resource;
use App\Http\Resources\UserCollection;
class WorkerResource extends Resource{
public function get_items($resource){
return [
'seekers_search_url'=>route('worker.seekers.search',
['user_id'=>$resource->getKey()]),
'all_seekers_url'=>route('worker.seekers.all', ['user_id'=>$resource->getKey()]),
'seekers'=>new UserCollection($resource->whenLoaded('seekers'))
];
}
}
class User extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
protected function base_params(){
return [];
}
public function toArray($request)
{
$base = $this->base_params();
$class = config("initializations.resources.user.{$this->first_role->role}");
if($class){
$resource = app()->make($class);
$base = array_merge($base, $resource->get_items($this));
}
}
}
Please note that I am creating an instance of WorkerResource which is my higher order made up resource using configuration file and calling it's get_items method with an instance of JsonResource but inside WorkerResource class method I cannot access whenLoaded method of $resource. Undefined!
Please or to participate in this conversation.