Laravel show form error with form element name as key

喜你入骨 提交于 2019-12-07 13:15:51

问题


I am trying to learn laravel. I know Codeigniter. In codeigniter3 I will get the form error as an array with key as the form name by using the function

$this -> form_validation -> error_array();

it will display like

array(
    'form_element1' => 'this field is required',
    'form_element2' => 'this field is required'
)

Is there any way in laravel 5 to do the same?

Please help. Any help could be appreciated


回答1:


Laravel controller uses ValidatesRequests trait which provides a validate method. Here is example how to validate a request:

namespace App\Http\Controllers;

class MyController extends Controller
{

    public function store(Request $request)
    {
        $this->validate($request, [
            'subject' => 'required|max:255',
            'message' => 'required',
        ]);

        // All input is valid, do your task.
    }

}

If user inputs doesn't pass the rules of $this->validate() it will be automatically redirect your user back to the form view with old input and errors. The errors is held by $errors variable which is an instance of Illuminate\Support\MessageBag, to display it on your view:

@if (count($errors) > 0)
    <div class="error">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Or you can get error by key:

@if($errors->has('subject'))
    {{ $errors->first('subject');}} // Printed: Subject field is required.
@endif

To answer your question about how to display errors like in CI you can use toArray() method of Illuminate\Support\MessageBag:

$errors->toArray()

Manual Validation

You may also use validator instance manually using the Validator facade, like this:

namespace App\Http\Controllers;

use Validator;

class MyController extends Controller
{

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'subject' => 'required|max:255',
            'message' => 'required',
        ]);

        if ($validator->fails()) {
            return redirect('your-form-uri')->withErrors($validator)->withInput();
        }

        // All input is valid, do your task.
    }

}

Again you can get the errors from $errors variable as above.

Form Request Validation

To use this method, you can start by creating a form validation request using artisan CLI:

 php artisan make:request ContactRequest

It will create you a ContactRequest class, you can find it in app/Http/Request/ folder.

namespace App\Http\Requests;

use App\Http\Requests\Request;

class ContactRequest extends Request
{
    /**
     * 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 [
            'subject' => 'required|max:225',
            'message' => 'required',
        ];
    }
}

On your controller method variable instead of using Request $request you may use ContactRequest $request:

namespace App\Http\Controllers;

use App\Http\Requests\ContactRequest;

class MyController extends Controller
{

    public function store(ContactRequest $request)
    {
        // All input is valid, do your task.
    }

}

If user input passes it will continue to execute your code on that method otherwise user will be redirected back to form view, and of course you can display the errors the same as two method above.




回答2:


you can set a return from controller

return redirect()->back()->withErrors($request->all());

or

return redirect()->back()->withErrors(Input::all());

and you can print errors in view as

@if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> There were some problems with your input.<br><br>
            <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
            </ul>
        </div>
    @endif



回答3:


This will display each error message attached to its key:

@foreach($errors->getMessages() as $key => $error)
    {{$key}}: {{$error[0]}}
@endforeach


来源:https://stackoverflow.com/questions/37496025/laravel-show-form-error-with-form-element-name-as-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!