Search code examples
phptwitter-bootstraplaravellaravel-5flash-message

Laravel flash message showing after refresh


I have one problem. I am building one application with Laravel and on the page where I upload the picture I need one flash success message that says you successfully uploaded new picture. When I upload, it works, shows the flash message, but when I refresh, or i go to other page, the message still stays there. And then after another refresh it disappears. On other pages like creating new post, the flash message works properly without showing after the refresh or going to another page. I am using imageintervention.io api for uploading image, I'm mentioning it because I don't want you to get confused with the code.

public function update_avatar(Request $request)
{
    // Handle the upload of avatar
    if ($request->hasFile('avatar')) 
    {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();

        Image::make($avatar)->resize(300, 300)->save( public_path('/uploads/avatars/' . $filename ) );

        $user = Auth::user();
        $user->avatar = $filename;
        $user->save();

        Session::flash('success', 'You have successfully uploaded new picture!');       


    }

    return view('pages.profile', array('user' => Auth::user()) );

}

Solution

  • You should not be returning a view after the action you are doing like that. You should be returning a redirect to a GET route where you will be displaying that view instead (view - pages.profile). This is the POST redirect GET flow.

    Flashed data is only available on the NEXT request. You are flashing in the same request you are displaying a view. That is why the refresh is then showing the flash message, because the refresh is causing a new request, which is the next request.

    You really shouldn't have a single method doing form processing and displaying of views as it will cause confusion down the road.

    Have a method that does the processing which redirects to a route that displays your view. You can flash and redirect at the same time.

    return redirect()->route(...)->with('success', ....);