statix-php/laravel-form-actions

Laravel 表单请求与动作的混合

0.0.3 2023-09-02 06:06 UTC

README

Latest Version on Packagist Total Downloads

Laravel 表单动作结合了 Spatie 的 Laravel 数据和 Laravel 的表单请求的最佳特性,从而生成一个强大且高效的包,简化了 Laravel 应用程序中的表单处理。

安装

您可以通过运行以下命令轻松使用 Composer 安装此包。有关更多详细信息,请访问Packagist 页面

composer require statix-php/laravel-form-actions

创建 FormActions

类似于 Laravel 表单请求,您可以使用以下命令使用 Artisan 创建新的 FormAction

php artisan make:form-action ActionName

此命令将在 app\Actions 目录中生成名为 ActionName 的类。类的初始内容如下

<?php 

namespace App\Actions;

use Statix\FormAction\FormAction;

class ActionName extends FormAction
{
    public function authorized(): bool
    {
        return true;
    }

    public function handle()
    {
        // Do cool things, tell people - Aaron Francis
    }
}

一旦创建了这个动作,您就可以开始构建它。让我们演示如何使用动作来创建新的 User

<?php 

namespace App\Actions;

use App\Models\User;
use Statix\FormAction\FormAction;
use Statix\FormAction\Validation\Rules;

class ActionName extends FormAction
{
    #[Rules(['required', 'string', 'min:3', 'max:255'])] 
    public $name;

    #[Rules(['email', 'unique:users,email'])] 
    public string $email;

    public ?string $timezone;

    public function authorized(): bool 
    {
        return true;
    }

    public function handle(): User
    {
        return User::create([
            'name' => $this->name,
            'email' => $this->email,
            'timezone' => $this->timezone ?? 'UTC',
        ]);
    }
}

有了这个动作,让我们将其集成到我们的路由中。

// routes/web.php

use App\Actions\ActionName;

Route::post('/register', function(ActionName $action) {

    $user = $action->handle();

    auth()->login($user);

    return redirect()->route('dashboard');
});

不需要手动进行授权或验证调用。就像 Laravel 的 FormRequest 一样,当它们从容器中解析时,这些动作会自动处理授权和验证。(此行为可以禁用)。

太棒了,现在让我们为这个动作编写一些测试!

测试

composer test

变更日志

请参阅CHANGELOG,了解更多最近的变化信息。

贡献

请参阅CONTRIBUTING以获取详细信息。

安全漏洞

对于任何潜在的安全漏洞,请直接联系我。

致谢

许可证

MIT 许可证(MIT)。请参阅许可证文件获取更多信息。