PHP code example of aqjw / resource-typeable

1. Go to this page and download the library: Download aqjw/resource-typeable library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

aqjw / resource-typeable example snippets


use Aqjw\ResourceTypeable\ResourceTypeable;
...
class ProductResource extends JsonResource
{
    use ResourceTypeable;
...

use Aqjw\ResourceTypeable\ResourceTypeable;
...
class ProductResource extends JsonResource
{
    use ResourceTypeable;

    /**
     * Tiny product resource
     * 
     * @return array
     */
    public function tiny($request): array
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'slug' => $this->slug,
            'price' => $this->price,
        ];
    }

    /**
     * Full product resource
     * 
     * @return array
     */
    public function full($request): array
    {
        return array_merge(
            $this->tiny($request),
            [
                'brand' => $this->brand,
                'model' => $this->model,
                'material' => $this->material,
                'size' => $this->size,
                'tags' => $this->tags,
                'color' => $this->color,
                'print' => $this->print,
            ],
        );
    }
}

...
class ProductController extends Controller
{
    ...
    public function index()
    {
        $products = Product::paginate(9);

        return new ProductCollection($products); // will return tiny resource type
        // or
        return ProductCollection::make($products); // will return tiny resource type
        // or
        return ProductResource::collectionType('full', $products); // will return full resource type
    }
    ...

...
class ProductController extends Controller
{
    ...
    public function show(Product $product)
    {
        return ProductResource::makeType('full', $product);
    }
    ...

use Aqjw\ResourceTypeable\ResourceTypeable;
...
class ProductResource extends JsonResource
{
    use ResourceTypeable;

    /**
     * Resource type
     * 
     * @var string
     */
    protected static $resource_type = 'full';
    ...