Skip to content

Instantly share code, notes, and snippets.

@hailwood
Created November 12, 2017 23:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hailwood/27d5db537d3ccee1e979645cc0c12a07 to your computer and use it in GitHub Desktop.
Save hailwood/27d5db537d3ccee1e979645cc0c12a07 to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Resources;
use App\Models\CropType;
use Illuminate\Http\Resources\Json\ResourceCollection;
class CropTypeCollectionResponse extends ResourceCollection
{
/**
* Transform the resource into a JSON array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return $this->collection->map(function (CropType $cropType) {
return new CropTypeResponse($cropType);
})->all();
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Resources\CropTypeCollectionResponse;
use App\Http\Resources\CropTypeResponse;
use App\Models\CropType;
use Illuminate\Http\Request;
class CropTypeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return CropTypeCollectionResponse
*/
public function index()
{
return new CropTypeCollectionResponse(CropType::paginate());
}
}
<?php
namespace App\Http\Resources;
class CropTypeResponse extends ResourceResponse
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request
* @return array
*/
public function toArray($request)
{
return parent::withPermissions(parent::toArray($request));
}
}
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
abstract class ResourceResponse extends Resource
{
public function withPermissions($representation)
{
$user = \Auth::user();
$representation['allowed_actions'] = [
'create' => $user->can('store', get_class($this->resource)),
'read' => $user->can('show', $this->resource),
'update' => $user->can('update', $this->resource),
'delete' => $user->can('delete', $this->resource)
];
return $representation;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment