如何将消息传递到Laravel中的另一个页面?

时间:2016-10-22 20:25:22

标签: php laravel error-handling

我有一个像这样的控制器

public function add(Requests\contactValidation $request){

    if(Auth::check()) {
        $new_array = array();
        $new_array['name'] = $request->name;
        $new_array['email'] = $request->email;
        $new_array['content'] = $request->content;
        contact::create($new_array);
        return back();
    } else {
        return back()->withError('you are not log in');
    }
}

我有视图

<?php
    echo "<pre>";
    print_r( $errors->all());
?>

结果:

Array
(
    [0] => you are not log in
)

我的问题:如何为该邮件设置名称?我想要这样的结果:

Array
(
    [Name] => you are not log in
)

2 个答案:

答案 0 :(得分:2)

您可以使用withErrors()将数组(键值)与消息(而不是withError())放在一起。

例如:

return back()->withErrors(['Name' => 'you are not log in']);
在您的视图中,您也可以致电:

@if( $errors->any() )
<span> {{$errors->first()}} </span>
@endif

答案 1 :(得分:0)

这就是我通常做的事情:

return Redirect::to('users/register')->with('message', 'The following errors occurred')->withErrors($validator)->withInput();

所以,基本上你可以使用存储为会话的消息/消息返回,显然也可以返回错误。另外,您可以查看以下link文档以获取详细信息。

此外,您可以将它们打印为:

@if(Session::has('message'))
      <p class="alert">{!! Session::get('message') !!}</p>
      @foreach($errors->all() as $error)
          <p>{!! $error !!}</p>
      @endforeach
@endif

显然,您可以根据自己的要求进行更改。希望它有所帮助。