Skip to content

Instantly share code, notes, and snippets.

@bayareawebpro
Last active March 11, 2020 20:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bayareawebpro/c98fb7c794d84665d8a06161a6561a8d to your computer and use it in GitHub Desktop.
Save bayareawebpro/c98fb7c794d84665d8a06161a6561a8d to your computer and use it in GitHub Desktop.
<?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";
}
}
@bayareawebpro
Copy link
Author

$user->toResourceArray(MyResource::class);

@christopherarter
Copy link

christopherarter commented Mar 11, 2020

Riffing on your snippet above to auto detect the common naming pattern so the resource class is optional

trait Resourceable
{
    public function toResourceArray(string $class = null, $request = null) : array
    {
        if (!$class) {
            $class = $this->resolveResourceName();
        }

        if ( $class 
            && class_exists($class)
            && is_subclass_of($class,JsonResource::class) ) {
            return (new $class($this))->resolve($request);
        }

        return $this->toArray();
    }

    private function resolveResourceName()
    {
        return (class_exists(self::class . 'Resource')) ?? null;
    }
}

so that should allow

$user->toResourceArray()

assuming a naming convention of UserResource class.

@bayareawebpro
Copy link
Author

@christopherarter Nicely Done!

@bayareawebpro
Copy link
Author

@christopherarter
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment