laravel 验证请求并在没有上一页时显示错误消息

n3h0vuf2  于 2023-02-25  发布在  其他
关注(0)|答案(1)|浏览(113)

我在Laravel 9应用程序中有以下函数:

Route::get('/update-appointment-status/{uuid}/{status}', [App\Http\Controllers\LeadController::class, 'updateAppointmentStatus'])->name('update-appointment-status');

public function updateAppointmentStatus(Request $request, LeadService $leadService, string $uuid, int $status)
{
    $validation = $request->validate([
        'uuid' => ['required', 'uuid'],
        'status' => ['required', 'numeric', Rule::in(Lead::STATUSES)],
    ]);
    
    $lead = Lead::where('uuid', $uuid)->firstOrFail();

    $leadService->updateStatus($lead, $status);

    return view('leads.update-status')->with(compact('lead'));
}

链接是从电子邮件内部访问的,这意味着没有“上一页”。我如何在视图内部显示错误消息?现在应用程序被重定向到存在验证错误的基本URL。

plicqrtu

plicqrtu1#

一个解决方案是创建一个“表单请求验证”,您可以使用Laravel文档了解如何实现此功能:https://laravel.com/docs/9.x/validation#form-request-validation
然后,在创建表单请求验证之后,可以使用$redirect属性定义重定向URL,并将其放入表单请求验证中:https://laravel.com/docs/9.x/validation#customizing-the-redirect-location

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SomeRequest extends FormRequest
{
    /**
     * The URI that users should be redirected to if validation fails.
     *
     * @var string
     */
    protected $redirect = '/path-to-page';

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'uuid' => ['required', 'uuid'],
            'status' => ['required', 'numeric', Rule::in(Lead::STATUSES)],
        ];
    }
}

相关问题