-1

我正在使用 laravel 表单请求验证来验证从视图到控制器的请求。我正在使用php artisan make:request SpecializedRequest。但是当验证失败时它不会返回并给出错误 422。我查看了laravel 文档,但我并不真正理解它。我如何确保验证失败它返回到上一页并显示错误消息我的表单请求验证

<?php

namespace Modules\Specialized\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Modules\Specialized\Entities\Specialized;

class SpecializedRequest extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
        ];
    }

    /**
     * Get the error messages for the defined validation rules.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'name.required' => 'Nama Specialized cannot be empty',
        ];
    }

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

我的控制器

/**
     * Store a newly created resource in storage.
     * @param  SpecializedRequest $request
     * @return Response
     */
    public function store(SpecializedRequest $request)
    {
        $specialized = Specialized::create($request->validated());
        return ($specialized) ? back()->withSuccess('Data has been added') : back()->withError('Something wrong') ;
    }

我的刀片

<form action="{{ route('specialized.store') }}" method="{{ $method }}" class="form-horizontal">
    @csrf   
    <fieldset class="content-group">
        <div class="form-group">
            <label for="name" class="control-label col-lg-2">Name</label>
            <div class="col-lg-10">
                <input type="text" name="name" class="form-control" value="{{ old('name',isset($specialized->name) ? $specialized->name : '') }}">
                <span style="color:red;"> {{$errors->first('name')}} </span>
            </div>
        </div>

    </fieldset>


    <div class="text-right">
        <button type="submit" class="btn btn-primary">Submit <i class="icon-arrow-right14 position-right"></i></button>
    </div>
</form>

尝试了同样的结果

public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required',
        ]);
        $specialized = Specialized::create($data->validated());
        return ($specialized) ? back()->withSuccess('Data has been added') : back()->withError('Something wrong') ;
    }
4

1 回答 1

0

你正在使用哪个版本的 laravel?

我认为你不需要:

$specialized = Specialized::create($request->validated());

尝试:

$specialized = Specialized::create($request->all());
return redirect()->back() ;

然后处理刀片中的错误显示,例如:

@if($errors->any()){{ implode('', $errors->all('<div>:message</div>')) }}@endif

另外,我相信您需要:

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

在您的 SpecializedRequest 中。

我希望这有帮助。

于 2021-01-05T07:40:49.017 回答