marvinrabe/laravel-wizards

Laravel 简单向导控制器。

0.4.0 2022-03-04 15:05 UTC

This package is auto-updated.

Last update: 2024-08-29 06:01:53 UTC


README

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Laravel 简单向导控制器。如果你需要一个更复杂的解决方案,那么请查看 Laravel Aracanist

安装

使用 composer 安装此包

composer require marvinrabe/laravel-wizards

用法

使用 wizard 宏在你的 web.php 中注册路由

Route::wizard('order', OrderWizardController::class);

为你的向导创建一个控制器。例如 OrderWizardController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use MarvinRabe\LaravelWizards\Wizard;
use MarvinRabe\LaravelWizards\WizardController;

class OrderWizardController extends WizardController
{
    // Prepare a payload. This payload will be available in $wizard->payload on each step. It will be saved
    // automatically after each step{number}Submit method. It is used to store each partial result until onFinish.
    // The simplest payload is an array. But you could use anything you want. It only needs to be serializable!
    public function preparePayload(Request $request, Wizard $wizard): array
    {
        return [];
    }

    // A step is simply a method with the name step{number}.
    // You can do anything you want! Return a view, redirect to somewhere else, etc.
    public function step1(Request $request, Wizard $wizard): mixed
    {
        return view('order.payment');
    }

    // For each step there might be a submit action with the name step{number}Submit. This will be called on POST.
    // In here you could validate the request and afterwards store it in the prepared payload like so:
    public function step1Submit(Request $request, Wizard $wizard): void
    {
        $request->validate([
            'credit_card' => ['required', 'string']
        ]);

        $wizard->payload['credit_card'] = $request->boolean('credit_card');
    }

    // You don't have to specify a step2Submit. If you omit this method the wizard will simply jump to the next step.
    // In each step you have access to the previously populated payload. By default it is stored in the session.
    public function step2(Request $request, Wizard $wizard): mixed
    {
        return view('order.summary', [
            'credit_card' => $wizard->payload['credit_card']
        ]);
    }
    
    // Continue with more step{number} and step{number}Submit methods. As many as you like!
    
    // After the last step the onFinish method will be called instead of the step{number}Submit.
    // The wizard will be deleted from the session and is no longer available.
    public function onFinish(Request $request, Wizard $wizard): mixed
    {
        // Do something! This is your final chance.
        return view('order.success');
    }
}

导航到 /orders 以启动向导。每个向导都有一个唯一的 ID,默认情况下存储在当前会话中。URL 遵循以下约定

/{name}/{id?}/{step?}

对于我们的上一个示例,实际的 URL 可能如下所示 /order/6e00f3db-c1c9-48b7-a90b-0081f75ed56c/2

如果缺少 ID,它将使用 preparePayload 创建一个新的向导实例。如果缺少步骤,它将从最后一个步骤继续向导。

许可证

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