Home > Enterprise >  Laravel - HTTP Session Flash Data dont work
Laravel - HTTP Session Flash Data dont work

Time:07-09

The Laravel documentation:

Sometimes you may wish to store items in the session for the next request. You may do so using the flash method.

$request->session()->flash('status', 'Task was successful!');

my code:

 public function store(StorePost $request)
    {
        $validated = $request->validate();

        $post = new Posts();
        $post->title = $validated['title'];
        $post->content = $validated['content'];

        $post->save();

        $request->session()->flash('status', 'Task was successful!');

        return redirect()->route('posts.show', [$post->id]);
    }

and my IDE vscode throw error looks like this: error in flash

Some help in this error ?

CodePudding user response:

A few things to fix your issue and clean things up a tad. The Laravel convention for naming models is to use the singular name of the table. If you have a table named posts, the model's name should be Post. Second, you don't need a temporary variable for the the validated data, just inline it. Finally, you can use with on your redirect to flash your session data:

    public function store(StorePost $request)
    {
        $post = Posts::create([
            'title'   => $request->validated('title'),
            'content' => $request->validated('content')
        ]);

        return redirect()->route('posts.show', $post)
            ->with('status', 'Task was successful!');
    }

CodePudding user response:

have you include the following namespace

use Session;

if not use 'Session' namespace

you can also try another way

public function store(StorePost $request)
    {
        $validated = $request->validate();

        $post = new Posts();
        $post->title = $validated['title'];
        $post->content = $validated['content'];

        $post->save();

        return redirect()->route('posts.show', [$post->id])->with('status','Task was successful!');
    }

it will create a RedirectResponse instance and flash data to the session in a single, fluent method

  • Related