smajti1 / laravel-wizard
laravel 的向导组件。
v1.7.2
2023-12-07 20:40 UTC
Requires
- php: ^7.3 || ^8.0
- illuminate/http: >=7.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^10.5
README
简单的laravel分步向导
安装
$ composer require smajti1/laravel-wizard
示例/如何使用
-
添加路由
use App\Http\Controllers\UserWizardController; Route::get('wizard/user/{step?}', [UserWizardController::class, 'wizard'])->name('wizard.user'); Route::post('wizard/user/{step}', [UserWizardController::class, 'wizardPost'])->name('wizard.user.post');
-
创建步骤
在composer.json文件中添加autoload字段
... "autoload": { "psr-4": { ... "App\\Wizard\\Steps\\": "app/Steps" }, ...
重新生成自动加载器
$ composer dump-autoload
创建步骤 app/Steps/SetUserNameStep.php
namespace App\Wizard\Steps; class SetUserNameStep extends \Smajti1\Laravel\Step { public static $label = 'Set user name'; public static $slug = 'set-user-name'; public static $view = 'wizard.user.steps._set_user_name'; public function process(\Illuminate\Http\Request $request) { // for example, create user ... // next if you want save one step progress to session use $this->saveProgress($request); } public function rules(\Illuminate\Http\Request $request = null): array { return [ 'username' => 'required|min:4|max:255', ]; } }
-
创建控制器
public $steps = [ 'set-username-key' => SetUserNameStep::class, SetPhoneStep::class, ... ]; protected $wizard; public function __construct() { $this->wizard = new Wizard($this->steps, $sessionKeyName = 'user'); } public function wizard($step = null) { try { if (is_null($step)) { $step = $this->wizard->firstOrLastProcessed(); } else { $step = $this->wizard->getBySlug($step); } } catch (StepNotFoundException $e) { abort(404); } return view('wizard.user.base', compact('step')); } public function wizardPost(Request $request, $step = null) { try { $step = $this->wizard->getBySlug($step); } catch (StepNotFoundException $e) { abort(404); } $this->validate($request, $step->rules($request)); $step->process($request); return redirect()->route('wizard.user', [$this->wizard->nextSlug()]); }
-
添加基本视图 $wizard 变量现在与视图自动共享
<ol> @foreach($wizard->all() as $key => $_step) <li> @if($step->index == $_step->index) <strong>{{ $_step::$label }}</strong> @elseif($step->index > $_step->index) <a href="{{ route('wizard.user', [$_step::$slug]) }}">{{ $_step::$label }}</a> @else {{ $_step::$label }} @endif </li> @endforeach </ol> <form action="{{ route('wizard.user.post', [$step::$slug]) }}" method="POST"> {{ csrf_field() }} @include($step::$view, compact('step', 'errors')) @if ($wizard->hasPrev()) <a href="{{ route('wizard.user', ['step' => $wizard->prevSlug()]) }}">Back</a> @else <a href="#">Back</a> @endif <span>Step {{ $step->number }}/{{ $wizard->limit() }}</span> @if ($wizard->hasNext()) <button type="submit">Next</button> @else <button type="submit">Done</button> @endif </form>
许可协议
Laravel wizard 是开源软件,许可协议为MIT 协议