Search code examples
phplaravellaravel-5flash-message

Laravel 5.2.35 - can't set Session::flash


Today I tried to set Session::flash('alert-info', 'This is a message') in my Laravel 5.2.35 project. But it won't display.

I removed the web middleware from the routes.php. But it still not work.

Routes.php

Route::group(['prefix' => 'client/{administration_id}', 'middleware' => ['loggedin']], function() {
    Route::get('/projects', ['as' => 'client.projects', 'uses' => 'ProjectController@listProjects']);
    Route::get('/project/new', ['as' => 'client.project.create', 'uses' => 'ProjectController@newProject']);
    Route::post('/project/new', ['as' => 'client.project.create.save', 'uses' => 'ProjectController@saveNewProject']);
});

ProjectController.php

<?php

namespace App\Http\Controllers;

use App\Projects;
use App\Http\Requests;
use Session;

class ProjectController extends Controller
{
    public function newProject($administration_id) {
        $customers = Customer::where('administration_id', $administration_id)->get();

        return view('client.projects.create', compact('customers'));
    }

    public function saveNewProject(Request $request, $administration_id) {

        $project = new Projects();
        $project->name = $request->name;
        $project->project_number = $request->code;
        $project->administration_id = $administration_id;
        $project->customer_id = $request->customer;

        if($project->save()) {
            Session::flash('alert-info', trans('projects.projects.create.success'));

            return redirect(route('client.projects', $administration_id));
        } else {
            Session::flash('alert-warning', trans('projects.projects.create.failure'));
            return redirect()->back();
        }
    }
}

Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'loggedin' => [
        'auth',
    ],

    'api' => [
        'throttle:60,1',
    ],
];

Solution

  • I removed middleware web from the RouteServiceProvider.php.

    Old code:

    protected function mapWebRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace, 'middleware' => 'web',
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    }
    

    New code:

    protected function mapWebRoutes(Router $router)
    {
        $router->group([
            'namespace' => $this->namespace,
        ], function ($router) {
            require app_path('Http/routes.php');
        });
    }
    

    After this it works fine, I don't know if someone else has the same problem but maybe this can be a solution.