项目作者: mtvs

项目描述 :
Approval process for Laravel Eloquent models
高级语言: PHP
项目地址: git://github.com/mtvs/eloquent-approval.git
创建时间: 2017-11-27T09:29:06Z
项目社区:https://github.com/mtvs/eloquent-approval

开源协议:MIT License

下载


Build Status

Eloquent Approval

Approval process for Laravel’s Eloquent models.

eloquent-approval-preview

Why we need content approval in our apps

Unless you’re comfortable with unacceptable content, spam and any other
violations that may appear in what the users post, you need to include some
sort of content approval in your app.

Why approval process with three states

Although it’s possible to approve a model by using a boolean field but a field
that has three possible values: pending, approved and rejected gives us more
power. It differentiates between the models waiting for the decision and the
rejected ones and also makes it clear for the user if their content gets rejected.

How it works

After the setup, when new entities are being created, they are marked as
pending. Then their status can be changed to approved or rejected.

Also, when an update occurs that modifies attributes that require approval the
entity becomes suspended again.

By default the approval scope is applied on every query and filters out the
pending and rejected entities, so only approved entities are included.
You can include the entities that aren’t approved by explicitly specifying it.

Install

  1. $ composer require mtvs/eloquent-approval

Setup

Registering the service provider

By default the service provider is registered automatically by Laravel package
discovery otherwise you need to register it in your config\app.php

  1. Mtvs\EloquentApproval\ApprovalServiceProvider::class

Database

The following method adds two columns to the schema, one to store
the approval status named approval_status and another to store the timestamp at which the
last status update is occurred named approval_at.

  1. $table->approvals()

You can change the default column names but then you need to specify them on the model too.

Model

Add Approvable trait to the model

  1. use Illuminate\Database\Eloquent\Model;
  2. use Mtvs\EloquentApproval\Approvable;
  3. class Entity extends Model
  4. {
  5. use Approvable;
  6. }

If you want to change the default column names you need to specify them
by adding class constants to your model

  1. use Illuminate\Database\Eloquent\Model;
  2. use Mtvs\EloquentApproval\Approvable;
  3. class Entity extends Model
  4. {
  5. use Approvable;
  6. const APPROVAL_STATUS = 'custom_approval_status';
  7. const APPROVAL_AT = 'custom_approval_at';
  8. }

Add approval_at to the model $dates list to get Carbon instances when accessing it.

Approval Required Attributes

When an update occurs that modifies attributes that require
approval, the entity becomes suspended again.

  1. $entity->update($attributes); // an update with approval required modification
  2. $entity->isPending(); // true

Note that this happens only when you perform the update on Model object
itself not by using a query Builder instance.

By default all attributes require approval.

  1. /**
  2. * @return array
  3. */
  4. public function approvalRequired()
  5. {
  6. return ['*'];
  7. }
  8. /**
  9. * @return array
  10. */
  11. public function approvalNotRequired()
  12. {
  13. return [];
  14. }

You can override them to have a custom set of approval required attributes.

They work like $fillable and $guarded in the Eloquent. approvalRequired() returns
the black list while approvalNotRequired() returns the white list.

Usage

Newly created entities are marked as pending and by default excluded from
queries on the model.

  1. Entity::create(); // #1 pending
  2. Entity::all(); // []
  3. Entity::find(1); // null

Including all the entities

  1. Entity::anyApprovalStatus()->get(); // retrieving all
  2. Entity::anyApprovalStatus()->find(1); // retrieving one
  3. Entity::anyApprovalStatus()->delete(); // deleting all

If you want to disable the approval scope totally on every query, you can set
the approvalScopeDisabled on the model.

  1. use Illuminate\Database\Eloquent\Model;
  2. use Mtvs\EloquentApproval\Approvable;
  3. class Entity extends Model
  4. {
  5. use Approvable;
  6. public $approvalScopeDisabled = true;
  7. }

Limiting to only a specific status

  1. Entity::onlyPending()->get(); // retrieving only pending entities
  2. Entity::onlyRejected()->get(); // retrieving only rejected entities
  3. Entity::onlyApproved()->get(); // retrieving only approved entities

Updating the status

On model objects

You can update the status of an entity by using provided methods on the Model
object.

  1. $entity->approve(); // returns bool if the entity exists otherwise null
  2. $entity->reject(); // returns bool if the entity exists otherwise null
  3. $entity->suspend(); // returns bool if the entity exists otherwise null

On Builder objects

You can update the status of more than one entity by using provided methods on Builder
objects.

  1. Entity::whereIn('id', $updateIds)->approve(); // returns number of updated
  2. Entity::whereIn('id', $updateIds)->reject(); // returns number of updated
  3. Entity::whereIn('id', $updateIds)->suspend(); // returns number of updated

Approval Timestamp

When you change the approval status of an entity its approval_at column updates.
Before the first approval action on an entity itsapproval_at is null.

Check the status of an entity

You can check the status of an entity using provided methods on Model objects.

  1. $entity->isApproved(); // returns bool if entity exists otherwise null
  2. $entity->isRejected(); // returns bool if entity exists otherwise null
  3. $entity->isPending(); // returns bool if entity exists otherwise null

Approval Events

There are some model events that are dispatched before and after each approval action.

Action Before After
approve approving approved
suspend suspending suspended
reject rejecting rejected

Also, there is a general event named approvalChanged that is dispatched whenever
the approval status is changed regardless of the actual status.

You can hook to them by calling the provided static methods, which are named
after them, and passing your callbacks. Or by registring observers with methods
with the same names.

  1. use Illuminate\Database\Eloquent\Model;
  2. use Mtvs\EloquentApproval\Approvable;
  3. class Entity extends Model
  4. {
  5. use Approvable;
  6. protected static function boot()
  7. {
  8. parent::boot();
  9. static::approving(function ($entity) {
  10. // You can halt the process by returning false
  11. });
  12. static::approved(function ($entity) {
  13. // $entity has been approved
  14. });
  15. // or:
  16. static::observe(ApprovalObserver::class);
  17. }
  18. }
  19. class ApprovalObserver
  20. {
  21. public function approving($entity)
  22. {
  23. // You can halt the process by returning false
  24. }
  25. public function approved($entity)
  26. {
  27. // $entity has been approved
  28. }
  29. }

Eloquent model events can also be mapped to your application event classes.

Duplicate Approvals

Trying to set the approval status to the current value is ignored, i.e.:
no event will be dispatched and the approval timestamp won’t be updated.
In this case the approval method returns false.

The Model Factory

Import the ApprovalFactoryStates to be able to use the approval states
when using the model factory.

  1. namespace Database\Factories;
  2. use Illuminate\Database\Eloquent\Factories\Factory;
  3. use Mtvs\EloquentApproval\ApprovalFactoryStates;
  4. class EntityFactory extends Factory
  5. {
  6. use ApprovalFactoryStates;
  7. public function definition()
  8. {
  9. //
  10. }
  11. }
  1. Entity::factory()->approved()->create();
  2. Entity::factory()->rejected()->create();
  3. Entity::factory()->suspended()->create();

Handling Approval HTTP Requests

You can import the HandlesApproval in a controller to perform the approval
operations on a model. It contains an abstract method which has to be implemented
to return the model’s class name.

  1. namespace App\Http\Controllers\Admin;
  2. use App\Http\Controllers\Controller;
  3. use App\Models\Entity;
  4. use Mtvs\EloquentApproval\HandlesApproval;
  5. class EntitiesController extends Controller
  6. {
  7. use HandlesApproval;
  8. protected function model()
  9. {
  10. return Entity::class;
  11. }
  12. }

The trait’s performApproval() does the approval and the request should be
routed to this method. It has the key and request parameters which are
passed to it by the router.

When do the routing, don’t forget to apply the auth and can middlewares for
authentication and authourization.

  1. Route::post(
  2. 'admin/enitiy/{key}/approval',
  3. 'Admin\EntitiesController@performApproval'
  4. )->middleware(['auth', 'can:perform-approval'])

The request must have a approval_status key with
one of the possible values: approved, pending, rejected.

Frontend Components

There are also some UI components here written for Vue.js and Bootstrap that
you can use. First install them using the approval:ui artisan command and
then register them in your app.js file.

Approval Buttons Component

Call <approval-buttons> and pass the current-status and the approval-url
props to be able to make HTTP requests to set the approval status.

It emits the approval-changed event when an approval action happens.
The payload of the event is an object with the new approval_status and
approval_at values. Use the event to modify the corresponding keys on the
entity that in turn should change the current-status prop on the following
cycle.

Approval Status Component

Call <approval-status> and pass the value prop to show the current status.

Inspirations

When I was searching for an existing package for approval functionality
on eloquent models I encountered hootlex/laravel-moderation
even though I decided to write my own package I got some helpful inspirations from that one.

I also wrote different parts of the code following the way that similar parts
of Eloquent itself is written.