I want to send different response base on user role in my controller, in 2 project I come with a way to approach this.
1- my first approach is having a resource for each response.
my controller is like this :
$user = $request->user;
$role = $user->role;
$firstPost = Post::where('user_id',$user->getKey())->first();
$postResourceBuilder = new PostResourceBuilder($firstPost,$role);
return $postResourceBuilder->getResource();
then in my PostResourceBuilder:
class PostResourceBuilder {
private $post;
private $role;
public function __construct($post,$role){
$this->post = $post;
$this->role = $role;
}
public function getResource(){
switch($this->role){
case 'Client':
return new ClientPostResource($this->post);
default :
return new DefaultPostResource($this->post);
}
}
}
but in another project I came with another approach:
2- I make a new Resource class and all my Resources extends it:
class BaseResource extends JsonResource
{
protected $mode = 'Default';
public function setMode($mode)
{
$this->mode = $mode;
}
public function toArray($request)
{
return call_user_func([$this,$this->getMethodName()],$request);
}
public function getDefaultResource($request)
{
return parent::toArray($request);
}
protected function getMethodName(){
$methodName = 'get'.$this->mode.'Resource';
return method_exists($this,$methodName) ? $methodName : 'getDefaultResource';
}
}
then in my PostResource :
class PostResource extends BaseResource
{
public function getClientResource($request)
{
//...
}
}
and in my controller :
$user = $request->user;
$role = $user->role;
$firstPost = Post::where('user_id',$user->getKey())->first();
$postResource = new PostResource($firstPost,$role);
$postResource->setMode($role);
// if it's collection
// $postResource->collection->each->setMode($role)
return $postResource;
after I doing these I wonder which one is better
from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2ruMHfn
via IFTTT
Aucun commentaire:
Enregistrer un commentaire