Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mozew's avatar
Level 6

How to get id in session?

I have an article and I want to after save, get in session current id of article for next page notes.

use Session;

public function store(Request $request)
{
            $article = new Article($request->all());
            $article->user_id = auth()->user()->id;
            $article->title = $request->title;
            $article->body = $request->body;
            $article->id = $request->session()->get('id');
            $article->description = $request->description;
            $article->save();
            return redirect()->route('notes.index')->with('id', $request->id);
}

In notes page has a input hidden for get session of article id.

     <input type="hidden" class="form-control" value="{{ Session::get('id') }}" name="id" id="id">
0 likes
10 replies
JohnBraun's avatar

If you want to store the ID of the newly saved article in the session, you should do that as follows in your controller:

public function store()
{
    // ...
    $article->save();
    
    session(['article_id' => $article->id]);

    return redirect()->route('notes.index')->with('id', $request->id);
}
JohnBraun's avatar

@IRANKHOSRAVI - That line of code stores the id of the saved article to the article_id key in the session. Then you can grab the id from the session using session()->get(‘article_id’)

Snapey's avatar

actually, its not a relation, so

session(['id' => $article->id]);
Snapey's avatar

But honestly, this code is as bad as your other, identical question about Order

Snapey's avatar

@jlrdw its not storage permissions. he's writing null into session. There is no model attribute article_id

JohnBraun's avatar

@SNAPEY - I see I've messed that up in my comments as well, I meant $article->id where I said $article_id (was typing on mobile when I replied). I've updated my comments above.

Please or to participate in this conversation.