Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - How to use/access session variables in a view?

Tags:

php

laravel

I only find information on how to save a session variable which works like this: $request->session()->put('key', 'value');

But how can I access the session in a blade view?

like image 806
Black Avatar asked Jan 04 '18 14:01

Black


People also ask

Can a user view session variables?

No, SESSION variables are on the server side so from the client's perspective, they cannot change them. That's one of the main reasons we use Sessions instead of cookies. Sessions are a simple way to store data for individual users against a unique session ID.

How do I access session variables?

You can access a session variable's value by using the global variable $_SESSION. In the example stated below, you will create another session with a variable that stores your name. session_start();

How do you set a session variable in Laravel?

The correct syntax for this is: Session::set('variableName', $value); For Laravel 5.4 and later, the correct method to use is put : Session::put('variableName', $value);


2 Answers

Just use session() helper to read the data:

{{ session('key') }}

Or:

{{ request()->session()->get('key') }}

If you want to store something, do this:

@php(session(['key' => 'value']))
like image 98
Alexey Mezenin Avatar answered Sep 24 '22 05:09

Alexey Mezenin


Its quite simple as core php, you can use its facade in blade or a method like,

{{Session::get('key')}}

Or by method like,

{{ session()->get('key') }}
like image 44
Ritesh Khatri Avatar answered Sep 26 '22 05:09

Ritesh Khatri