Laravel 5.2 重定向成功消息

2021-12-18 00:00:00 php laravel laravel-5.2

我正在尝试将成功消息返回到我的 laravel 主页.

return redirect()->back()->withSuccess('IT WORKS!');

由于某种原因,运行此代码后变量 $success 没有得到任何值.

我用来显示成功消息的代码:

@if (!empty($success))<h1>{{$success}}</h1>@万一

我已将主页和时事通讯页面添加到 routes.php 中的 Web 中间件组,如下所示:

Route::group(['middleware' => 'web'], function () {路线::认证();路由::get('/', function () {返回视图('家');});Route::post('/newsletter/subscribe','NewsletterController@subscribe');});

有人知道为什么这似乎不起作用吗?

解决方案

您应该从 routes.php 中删除 web 中间件.手动添加 web 中间件会导致 会话和在 Laravel 5.2.27 及更高版本中请求相关问题.

如果它没有帮助(仍然,保持 routes.php 没有网络中间件),你可以尝试一些不同的方法:

return redirect()->back()->with('message', 'IT WORKS!');

如果存在则显示消息:

@if(session()->has('message'))<div class="alert alert-success">{{ session()->get('message') }}

@万一

I'm trying to get a success message back to my home page on laravel.

return redirect()->back()->withSuccess('IT WORKS!');

For some reason the variable $success doesn't get any value after running this code.

The code I'm using to display the succes message:

@if (!empty($success))
    <h1>{{$success}}</h1>
@endif

I have added the home and newsletter page to the web middleware group in routes.php like this:

Route::group(['middleware' => 'web'], function () {
    Route::auth();

    Route::get('/', function () {
        return view('home');
    });

    Route::post('/newsletter/subscribe','NewsletterController@subscribe');
});

Does anyone have any idea why this doesn't seem to work?

解决方案

You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.

If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:

return redirect()->back()->with('message', 'IT WORKS!');

Displaying message if it exists:

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

相关文章