laraditz / action by raditzfarhan

Single action class for Laravel and Lumen to keep your application DRY
1,377
0
2
Package Data
Maintainer Username: raditzfarhan
Maintainer Contact: raditzfarhan@gmail.com (Raditz Farhan)
Package Create Date: 2020-06-17
Package Last Update: 2020-08-23
Language: PHP
License: MIT
Last Refreshed: 2024-04-26 03:25:29
Package Statistics
Total Downloads: 1,377
Monthly Downloads: 0
Daily Downloads: 0
Total Stars: 0
Total Watchers: 2
Total Forks: 0
Total Open Issues: 0

Laravel Action

Latest Stable Version Total Downloads License StyleCI

Single action class for Laravel and Lumen to keep your application DRY.

Installation

Via Composer

$ composer require laraditz/action

Configuration

The Laravel and Lumen configurations vary slightly, so here are the instructions for each of the frameworks.

Laravel

Edit the config/app.php file and add the following line to register the service provider:

'providers' => [
    ...
    Laraditz\Action\ActionServiceProvider::class,
    ...
],

Tip: If you're on Laravel version 5.5 or higher, you can skip this part of the setup in favour of the Auto-Discovery feature.

Lumen

Edit the bootstrap/app.php file and add the following line to register the service provider:

...
$app->register(Laraditz\Action\ActionServiceProvider::class);
...

Usage

You can use php artisan make:action <name> to create your action. For example, php artisan make:action CreateNewPost. By default you can find it in App/Actions folder.

Sample action file generated with some logic added as below:

namespace App\Actions;

use Laraditz\Action\Action;

class CreateNewPost extends Action
{
    // Optional
    public function rules()
    {
        return [
            'title' => 'required',
            'body' => 'required|min:10',
        ];
    }

    public function handle()
    {
        // Your logic goes here
        \App\Post::create($this->validated());

        // use $this->validated() to get all validated attributes based on rules.
        // You also can use $this->all() to retreive all attributes passed if there is no rules.
    }
}

You can totally remove the rules method if you are not using it or just leave it as is.

Now that you've created your action, you can call it in few ways as below:

Using plain object

$createNewPost = new CreateNewPost([
    'title' => 'My first post', 
    'body' => 'This is a post content'
]);

$createNewPost->now();

Using static method

CreateNewPost::now([
    'title' => 'My first post', 
    'body' => 'This is a post content'
]);

Using invokable

// routes/web.php
Route::post('posts', '\App\Actions\CreateNewPost');

Credits

License

MIT. Please see the license file for more information.