我对 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
正如您所看到的,此类将错误消息显示到 $errors 变量中? (它来自验证规则检索错误,那么它到底是什么?数组?还是什么?)
然后进入 Controller 类,我有这个 Controller 方法:
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 中,并返回显示此错误消息的 error.blade.php。
如何手动完成? (在这种情况下我没有使用验证规则,我必须通过代码来完成)
最佳答案
构建 View 时使用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 theIlluminate\View\Middleware\ShareErrorsFromSession
middleware, which is provided by theweb
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.
关于php - 如何从 Laravel 应用程序中的 Controller 方法手动将带有特定消息的错误页面返回到 $errors 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42926562/