我试图重定向到上一页的消息时,有一个致命的错误。

App::fatal(function($exception)
{
    return Redirect::back()->with('msg', 'The Message');
}

在视图中尝试访问msg

Sessions::get('msg')

但是什么都没有渲染,是我做错了吗?


当前回答

我自己不再为laravel写这篇文章,而是支持为您处理这一切的Laracasts包。它真的很容易使用,并保持您的代码干净。甚至还有一个laracast来说明如何使用它。你所要做的就是:

通过Composer导入包。

"require": {
  "laracasts/flash": "~1.0"
}

在app/config/app.php中包含服务提供者。

'providers' => [
  'Laracasts\Flash\FlashServiceProvider'
];

在底部的同一个文件中添加一个facade别名:

'aliases' => [
  'Flash' => 'Laracasts\Flash\Flash'
];

将HTML拖到视图中:

@include('flash::message') 

在消息的右侧有一个关闭按钮。这依赖于jQuery,所以请确保在引导之前添加它。

可选的变化:

如果你不使用bootstrap或者想要跳过flash消息的包含并自己编写代码:

@if (Session::has('flash_notification.message'))
  <div class="{{ Session::get('flash_notification.level') }}">
    {{ Session::get('flash_notification.message') }}
  </div>
@endif

如果你想查看@include('flash::message')拉进来的HTML,你可以在vendor/laracasts/flash/src/views/message.blade.php中找到它。

如果你需要修改部分做:

php artisan view:publish laracasts/flash

这两个包视图现在将位于' app/views/packages/laracasts/flash/'目录中。

其他回答

当我试图重定向时,我收到了这条消息:

public function validateLogin(LoginRequest $request){
    //

    return redirect()->route('sesion.iniciar')
            ->withErrors($request)
            ->withInput();

当正确的方式是:

public function validateLogin(LoginRequest $request){
    //

    return redirect()->route('sesion.iniciar')
            ->withErrors($request->messages())
            ->withInput();

对于拉拉维尔 5.6.*

在尝试Laravel 5.6提供的一些答案时。*,很明显已经有了一些改进,我将在这里发布,以方便那些无法找到解决方案的其余答案。

STEP 1:

转到你的控制器文件,在类之前添加这个:

use Illuminate\Support\Facades\Redirect;

步骤2: 将此添加到想要返回重定向的地方。

 return Redirect()->back()->with(['message' => 'The Message']);

步骤3: 转到刀片文件并按如下方式编辑

@if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
 @endif

然后测试一下,然后感谢我。

这应该适用于laravel 5.6。*和可能5.7.*

在Laravel 5.5中:

return back()->withErrors($arrayWithErrors);

在使用Blade的视图中:

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

Laravel 5.6。*

控制器

if(true) {
   $msg = [
        'message' => 'Some Message!',
       ];

   return redirect()->route('home')->with($msg);
} else {
  $msg = [
       'error' => 'Some error!',
  ];
  return redirect()->route('welcome')->with($msg);
}

叶片模板

  @if (Session::has('message'))
       <div class="alert alert-success" role="alert">
           {{Session::get('message')}}
       </div>
  @elseif (Session::has('error'))
       <div class="alert alert-warning" role="alert">
           {{Session::get('error')}}
       </div>
  @endif

Enyoj

与 Laravel 5.8 相关:

控制器

return back()->with('error', 'Incorrect username or password.');

叶片

  @if (Session::has('error'))
       <div class="alert alert-warning" role="alert">
           {{Session::get('error')}}
       </div>
  @endif