An open API service indexing awesome lists of open source software.

https://github.com/morning-train/laravelresources


https://github.com/morning-train/laravelresources

Last synced: 3 months ago
JSON representation

Awesome Lists containing this project

README

          

# Resources and Operations for Laravel
Operations are a set of actions on the server that handles all logic from setting up routes to handling client requests.

A simple operation could be an index operation for getting all users and returning them to the client.

Another use-case could be triggering an action on an Eloquent model.
When doing this, one would always have to validate user input, fetch the model,
execute the method and then perhaps return something meaningful to the user.

This is similar to a simple operation where we need to return a single instance of a model to the user
(a traditional read call) - but it contains some additional logic to handle method execution.

A delete operation is similar, in that it first fetches the model and the trigger the delete method on it.

## Install

Via Composer

``` bash
$ composer require morningtrain/laravel-resources
$ php artisan vendor:publish --provider="MorningTrain\Laravel\Resources\LaravelResourcesServiceProvider"
```

## Configuration
Register your resources and operations in `config/resources.php`:

The first level key corresponds to namespace, and value is an array of your resource classes.
You can give resources custom names with array keys, and nest arrays of resources. Just make sure all items have unique keys.

If no key is provided for a resource, the `Str::snake(class_basename($resource))` is used.
This means if you have a class called `User` and another resource with the key `"user"` in the same namespace, they will collide.

Example:
``` php
'api' => [
\App\Operations\Api\User::class,
'custom_user' => \App\Operations\Api\User::class,

'nested' => [
\App\Operations\Api\User::class,
'custom_user' => \App\Operations\Api\User::class,

'deep_nested' => [
\App\Operations\Api\User::class,
'custom_user' => \App\Operations\Api\User::class,
],

/*
* These two will not work together - non-unique resource name:
* \App\Operations\Api\MyResource::class,
* 'my_resource' => \App\Operations\Api\User::class,
*/
],
```

## Examples

### Index Operation
The purpose of the `Index` operation is to retrieve a list of model entries and return the list as JSON.

This code example is taken from the package and will illustrate how the Index operation is implemented.

```php
model($this->model)->filters($this->getCachedFilters()),

/**
* Trigger `get` on the query and returns the resulting collection
*/
QueryToCollection::create(),

/**
* Transform the collection by applying any appends to each model in the entry
*/
TransformToView::create()->appends($this->appends, $this->overwrite_appends),
];
}

}

```

On a project level, the Index class can be either implemented in a Resource or as a single Operation.

The following example is an `EloquentResource` implementing a single `Index` operation.
The operation is already added in the base class, so it is not really neccesary to have the static `$operations` property.

In our example, users are returned with a pagination filter applied.

```php
trigger('someModelMethod')
```

Or like this using a closure:

```php
\MorningTrain\Laravel\Resources\Support\Pipes\Eloquent\TriggerOnModel::create()
->trigger(
fn(Model $model) => $model->someModelMethod()
)
```

The *Action* eloquent operation is basically a *Read* operation with a TriggerOnModel pipe.

### TriggerOnModelsInCollection
The *TriggerOnModelsInCollection* pipe is similar to *TriggerOnModel*.
Instead of expecting a model, it expects a collection of models and will execute the trigger for exery model instance in the collection.

### QueryToCollection
Triggers *get* on the query returned by the previous pipe and returns the result.

### QueryToModel
Triggers *first* on the query returned by the previous pipe and returns the result.

### QueryToCount
Triggers *count* on the query returned by the previous pipe and returns the result.

### ToResourceView
It expects the previous pipe to return a Model or Collection instance.
The data (Model or Collection) will be passed into a [Laravel Resource](https://laravel.com/docs/8.x/eloquent-resources)
and the resulting array will be returned.

```php
\MorningTrain\Laravel\Resources\Support\Pipes\ToResourceView::create()
->view(MyResourceView::class)
```

Most Eloquent operations are already configured to use this pipe, so it will be possible to configure the resource like this:

```php
public function readOperation(Read $read)
{
$read->model(MyModel::class)
->resourceView(MyModelResource::class);
}
```

### SetEnv
This pipe sets context environment variables.
It is configurable using the *environment* method.

```php
\MorningTrain\Laravel\Resources\Support\Pipes\Context\SetEnv::create()
->environment(['env' => 'variable'])
```

The *environment* method is a proxy of `Context::env`,
which means that it will also be able to take a closure that is executed when the ENV is generated.

### BladeView
The *BladeView* pipe returns a blade view matching the configuration.

```php
\MorningTrain\Laravel\Resources\Support\Pipes\Pages\BladeView::create()
->path('path.to.blade.view')
->parameters(['blade' => 'parameters'])
```

### RespondWithPageEnv
The *RespondWithPageEnv* pipe return the current ENV from Context as the response
if it is an AJAX request. It can be used to get the ENV of a page by calling its route using Ajax.

```php
\MorningTrain\Laravel\Resources\Support\Pipes\Pages\RespondWithPageEnv::create()
```

## Credits
This package is developed and actively maintained by [Morningtrain](https://morningtrain.dk).

_- _ -__ - -- _ _ - --- __ ----- _ --_
( Morningtrain, Denmark )
`---__- --__ _ --- _ -- ___ - - _ --_ ´
o
. ____
_||__| | ______ ______ ______
( | | | | | | |
/-()---() ~ ()--() ~ ()--() ~ ()--()
--------------------------------------