php 从控制器重定向后在 Laravel 中显示错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26732821/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:01:49  来源:igfitidea点击:

Displaying the Error Messages in Laravel after being Redirected from controller

phplaravellaravel-4blade

提问by SA__

How can I display the validation message in the view that is being redirected in Laravel ?

如何在 Laravel 中重定向的视图中显示验证消息?

Here is my function in a Controller

这是我在控制器中的功能

public function registeruser()
{
    $firstname = Input::get('firstname');
    $lastname = Input::get('lastname');
    $data  =  Input::except(array('_token')) ;
    $rule  =  array(
                'firstname'       => 'required',
                'lastname'         => 'required',
                   ) ;
    $validator = Validator::make($data,$rule);
    if ($validator->fails())
    {
    $messages = $validator->messages();
    return Redirect::to('/')->with('message', 'Register Failed');
    }
    else
    {
    DB::insert('insert into user (firstname, lastname) values (?, ?)',
                                array($firstname, $lastname));
    return Redirect::to('/')->with('message', 'Register Success');
    }
    }

I know the below given code is a bad try, But how can I fix it and what am I missing

我知道下面给出的代码是一个糟糕的尝试,但是我该如何修复它以及我错过了什么

@if($errors->has())
    @foreach ($errors->all() as $error)
        <div>{{ $error }}</div>
    @endforeach
@endif

Update : And how do I display the error messages near to the particular fields

更新:以及如何在特定字段附近显示错误消息

回答by Sushant Aryal

Laravel 4

Laravel 4

When the validation fails return back with the validation errors.

当验证失败时返回验证错误。

if($validator->fails()) {
    return Redirect::back()->withErrors($validator);
}

You can catch the error on your view using

您可以使用

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

UPDATE

更新

To display error under each field you can do like this.

要在每个字段下显示错误,您可以这样做。

<input type="text" name="firstname">
@if($errors->has('firstname'))
    <div class="error">{{ $errors->first('firstname') }}</div>
@endif

For better display style with css.

使用 css 更好地显示样式。

You can refer to the docs here.

你可以参考这里的文档

UPDATE 2

更新 2

To display all errors at once

一次显示所有错误

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

To display error under each field.

在每个字段下显示错误。

@error('firstname')
    <div class="error">{{ $message }}</div>
@enderror

回答by Andrew

If you want to load the view from the same controller you are on:

如果您想从您所在的同一控制器加载视图:

if ($validator->fails()) {
    return self::index($request)->withErrors($validator->errors());
}

And if you want to quickly display all errors but have a bit more control:

如果您想快速显示所有错误但有更多控制权:

 @if ($errors->any())
     @foreach ($errors->all() as $error)
         <div>{{$error}}</div>
     @endforeach
 @endif

回答by Nicola Lamonaca

@if ($errors->has('category'))
    <span class="error">{{ $errors->first('category') }}</span>
@endif

回答by Roberto Lyra

$validator = Validator::make($request->all(), [ 'email' => 'required|email', 'password' => 'required', ]);

if ($validator->fails()) { return $validator->errors(); }

回答by Ali Raza

to Make it look nice you can use little bootstrap help

为了让它看起来不错,你可以使用一些引导程序帮助

@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
    </button>
    <ul class="p-0 m-0" style="list-style: none;">
        @foreach($errors->all() as $error)
        <li>{{$error}}</li>
        @endforeach
    </ul>
</div>
@endif

回答by rahul

{!! Form::text('firstname', null !!}

@if($errors->has('firstname')) 
    {{ $errors->first('firstname') }} 
@endif

回答by Vipertecpro

A New Laravel Blade Error Directive comes to Laravel 5.8.13

新Laravel刃错误指令涉及到Laravel 5.8.13

// Before
@if ($errors->has('email'))
    <span>{{ $errors->first('email') }}</span>
@endif

// After:
@error('email')
    <span>{{ $message }}</span>
@enderror

回答by Mayank

Move all that in kernel.php if just the above method didn't work for you remember you have to move all those lines in kernel.php in addition to the above solution

如果只是上述方法对您不起作用,请移动 kernel.php 中的所有内容,请记住,除了上述解决方案之外,您还必须移动 kernel.php 中的所有这些行

let me first display the way it is there in the file already..

让我首先显示它在文件中的方式..

protected $middleware = [

    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

now what you have to do is

现在你要做的是

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
     \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
];

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [

    ],

    'api' => [
        'throttle:60,1',
    ],
];

i.e.;

IE;

enter image description here

在此处输入图片说明