Laravel使用with()方法重定向并显示消息

225

在发生致命错误时,我正在尝试带有消息地重定向回上一页。

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

在尝试访问消息时

Sessions::get('msg')

但是什么都没有被渲染出来,我在这里做错了什么吗?


2
修正拼写错误 Sessions,并在需要的地方添加 use。除此之外 - 应该可以工作。 - Yevgeniy Afanasyev
25个回答

1

针对 Laravel 3

提醒一下 @giannis christofakis 的回答;对于使用 Laravel 3 的用户,请将

替换为 。
return Redirect::back()->withErrors(['msg', 'The Message']);

使用:

return Redirect::back()->with_errors(['msg', 'The Message']);

0
    **Try This**
    
    Try This Code 
    --- Controller ---

    return redirect('list')->with('message', 'Successfully');
    return redirect('list');
   
  ----  Blade view ------
    @if(session()->has('message'))
        <div class="alert alert-success">
            {{ session()->get('message') }}
        </div>
    @endif

0

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

0

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

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();

0
截至Laravel 9.19,如果您使用Session :: flush(),它将删除所有会话数据,因此您应该使用Session :: put()。
use Illuminate\Support\Facades\Session;
Session::put('msg', 'The Message');

If you want to store the data in an array use,
Session::push('msg','The message'); This will return an array in your view. 

现在您可以使用session()帮助函数在视图中访问会话数据。在您的情况下,将是:

session('msg')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接