如何手动 return 带有特定消息的错误页面从 Laravel 应用程序中的 Controller 方法进入 $errors?

How can manually return an error page with a specific message into the $errors from a Controller method in a Laravel application?

我在 PHP 和 Laravel 都是新手。我正在做一个 Laravel 5.4 项目,我遇到了以下问题。

我有一个名为 error.blade.php:

的自定义错误页面
@extends('layouts.app')

@section('content')

    <h1 class="page-header"><i class="fa fa-exclamation-triangle" aria-hidden="true" style="margin-right: 2%"></i>Riscontrati errori</h1>

    @if (count($errors) > 0)
        <div class="alert alert-danger">
            <strong>Whoops!</strong> Sono stati riscontrati errori nel tuo input.<br /><br />
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif


@endsection

如您所见,class 将错误消息显示到 $errors 变量中? (它来自验证规则检索错误,那么它到底是什么?数组?还是什么?)

然后进入一个控制器class我有这个控制器方法:

public function activate(ActivateRequest $request) {

    $email = $request->input('email');
    $token = $request->input('token');

    $results = DB::select('select * from pm_user where email = :email', ['email' => $email]);

    $tokenFromDB = $results[0]->token;

    if($token != $tokenFromDB) {
        // PUT AN ERROR INTO THE $errors ARRAY
        // RETURN THE error.blade.php VIEW
    }

    return 'Works!';
    // do stuff
}

因此,正如您在前面的代码片段中所见,我有这种情况:

if($token != $tokenFromDB) {
    // PUT AN ERROR INTO THE $errors ARRAY
    // RETURN THE error.blade.php VIEW
}

所以在这种特定情况下,我想在 $errors 和 return error.blade.php[ 中添加文本错误消息=35=] 显示此错误消息。

如何手动完成? (在这种情况下我没有使用验证规则,我必须通过代码来完成)

构建视图时使用 withErrors

return redirect('yourErrorBladeView')
   ->withErrors(['yourErrorName'=>'yourErrorDescription']);

或者没有重定向:

return View::make('yourErrorBladeView')
    ->withErrors(['yourErrorName'=>'yourErrorDescription']);

来自 Laravel 验证错误文档 (https://laravel.com/docs/5.4/validation#quick-displaying-the-validation-errors):

The $errors variable is bound to the view by the Illuminate\View\Middleware\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used.