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

TimonBirk's avatar

How to start a new session?

Hi,

for getting started with Laravel and sessions I have built a really simple controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class TestController extends Controller
{

    public function test(Request $request)
    {

        echo "Session id is " . $request->session()->getId(). "<br><br>";
        $request->session()->start();
        $data = $request->session()->all();
        echo "Session contains " . json_encode($data) . "<br><br>";

        $request->session()->put("testKey", "testValue");
        $data = $request->session()->all();
        echo "Session contains now " . json_encode($data) . "<br><br>";

        $request->session()->save();
    }
}

Mapped in the routes/web.php

Route::get('/test', 'TestController@test');

When I visit the path /test two-times I always get a new session id and my testKey is not set. How can I persist the session?

When I have visited the path / (which returnes the default welcome view) my session seems to be started and active and the testKey is successfully persisted in the session.

Thanks for your help!

0 likes
2 replies
jlrdw's avatar

You do not need to start a session, it's done for you.

TimonBirk's avatar

Ok, thank you! It seems to work on my laptop, only the browser on my workstation don't use the cookies?

Please or to participate in this conversation.