Adam
Adam

Reputation: 29019

Laravel: Check if session exists necessary?

Before I was using Laravel I did the following:

<input type="text" name="comment" value="<?php if(isset($_SESSION['comment'])) echo $_SESSION['comment']; ?>">

I had to check if $_SESSION['comment'] exists in order to prevent a warning. Now inside my blade files I can translate this to

<input type="text" name="comment" value="{{ (isset(session('comment')) ? session('comment') : ''}}">

But I wonder if it is still necessary to check if the session exists or if I can simply write

<input type="text" name="comment" value="{{ session('comment') }}">

I could not find that in the docs. I was looking in the API but I realized that I have no clue in which class I may find the global helper function..

Upvotes: 2

Views: 4255

Answers (1)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6637

You need not check if the session is started. It starts automatically for you in Laravel.

If you try to display a session(variable) which does not exist, you will get null.

But if you'd rather have a default value, you pass it as the second parameter:

var_dump(session('Lorem ipsum4', 'default value'));
// will result in: 
// "default value"

All the magic helper methods in laravel are placed in a file vendor/laravel/framework/src/Illuminate/Foundation/helpers.php. There you will find function session definition, somewhat as follows:

function session($key = null, $default = null)
{
    if (is_null($key)) {
        return app('session');
    }

    if (is_array($key)) {
        return app('session')->put($key);
    }

    return app('session')->get($key, $default);
}

Upvotes: 2

Related Questions