mardi 5 janvier 2021

Laravel form request validation return error

i'm using laravel form request validation to validate a request from view to controller. i'm using php artisan make:request SpecializedRequest. but when the validation fail it doesn't return back and it gave error 422. i've looked up at laravel documentation and i don't really understand it. How do i make sure if the validation fail it return back to previous page with error message my Form Request validation

<?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;
    }
}

my controller

/**
     * 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') ;
    }

my blade

<form action="" 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="">
                <span style="color:red;">  </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>

tried this same result

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') ;
    }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2XdVLEZ
via IFTTT

Aucun commentaire:

Enregistrer un commentaire