-
-
Save niladam/21815a50b1712fac8018258432def2af to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Concerns; | |
use Illuminate\Http\Request; | |
use Illuminate\Http\Resources\Json\JsonResource; | |
trait Resourceable | |
{ | |
public function toResourceArray(?string $class = null, ?Request $request = null): array | |
{ | |
$class = $class ?: $this->resolveResourceName(); | |
if (class_exists($class) && is_subclass_of($class, JsonResource::class)) { | |
return (new $class($this))->resolve($request); | |
} | |
return $this->toArray(); | |
} | |
protected function resolveResourceName(): string | |
{ | |
$reflect = new \ReflectionClass($this); | |
return "\\{$reflect->getNamespaceName()}\\Http\\Resources\\{$reflect->getShortName()}Resource"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment