Skip to content

HasResourceInterface

Kevin Upton edited this page Nov 30, 2017 · 4 revisions

The resource trait is an extension to the Laravel Controller resource, allowing for fully customizable CRUD, in only a couple lines.

Requirements

It is a requirement that the middleware of this package is implemented! (Please view the package for details on how to implement.)

  • This trait also requires the model to be an Ethereal model. Otherwise validation will not work on store and update. (Alternatively you could just implement the HasValidation trait on your model).

Implementation

An example implementation would be as follows:

Define a parent Controller (recommended)

<?php

namespace App\Http\Controllers;

use Kevupton\Ethereal\Traits\HasResourceInterface;

class ResourceController extends Controller
{
    use HasResourceInterface;
}

Define the Child Controller

namespace App\Http\Controllers;

use App\TestA;

class TestController extends ResourceController
{
    public static $class = TestA::class;
}

Define the Route

\App\Http\Controllers\TestController::routes();

// or

\App\Http\Controllers\TestController::routes(['index', 'store']); // for only those methods

To change the default path (which is the snake_case of the controller short name (excluding 'Controller')) use:

$path = 'my/custom/path';
$namespace = 'Auth';
$actionOverrides = [];
\App\Http\Controllers\TestController::routes(['index', 'store'], $path, $actionOverrides, $namespace);

Advanced Usage

Override the controller methods by creating or own based on one of the route keys: ['index', 'store', 'show', 'update', 'destroy']

<?php

namespace App\Http\Controllers;

use App\TestA;
use Illuminate\Http\Request;

class TestController extends ResourceController
{
    public static $class = TestA::class;
    
    protected function index (Request $request)
    {
        return ['my custom index'];
    }
}

exmaple route table:

Verb Path NamedRoute Controller Action Middleware
GET /v1/user v1.users.index App\Http\Controllers\User\UsersController index cors
POST /v1/user v1.users.store App\Http\Controllers\User\UsersController store cors
GET /v1/user/{id} v1.users.show App\Http\Controllers\User\UsersController show cors
PUT /v1/user/{id} v1.users.update App\Http\Controllers\User\UsersController update cors
DELETE /v1/user/{id} v1.users.destroy App\Http\Controllers\User\UsersController destroy cors