简体   繁体   中英

“ Laravel Session Array ” Printing a created session array in Laravel

I have created a session array in laravel using the code:

Session::put("backUrl", array($workout_id =>URL::previous()))   ;
  //or
Session::push("backUrl.$workout_id", URL::previous())   ;

Both works and it has been created successfully and I could see it in the debugger

'backUrl' => array(1) [
    '78' => string (36) "http://192.241.4.104/admin/view?cs=1"
]

now I am unable to print it, The code i have used is

echo Session::get("backUrl"[$workout_id]);

it shows a syntax error, unexpected '[' error

And I have also used

echo Session::get("backUrl[$workout_id]"); 

nothing works

Because you keyed your entire array under the session variable "backurl".

if you var_dump:

var_dump(Session::get("backUrl")):

I am pretty sure you get:

array(
    [2] => "http://previous-url"
)

So wether you go like this:

$lastUrl = Session::get("backUrl");
echo array_keys($lastUrl)[0]; //workout-ID
echo array_values($lastUrl)[0]; //Value

Or you save your two variables seperately:

Session::put("backUrl", URL::previous());
Session::put("lastWorkoutId", $workout_id);

And then read them individually:

Session::get("backUrl");
Session::get("lastWorkoutId");

After several trials I have got what I wanted a session array for back button URL and thanks to @Steini for his valuable suggestions. I am posting this as it could be useful to someone...

At first I have changed using

Session::put("backUrl", array($workout_id =>URL::previous()))   ;

to

Session::put("backUrl.$workout_id", URL::previous())    ;

Saw the Session::push tag in Laravel Docs and tried luckly it worked. Because the first one deletes the existing session array and creates a new one.

And printing the Laravel session array is as simple as printing a session with added suffix

Session::get("sessionArrayName")['id']
   (i.e)
Session::get("backUrl")[$workout_id];

Thus got my session array printed and used it for my back button....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM