Skip to content

Instantly share code, notes, and snippets.

@lozadaOmr
Last active February 27, 2018 03:51
Show Gist options
  • Save lozadaOmr/f9c079ba82f49a2ece82 to your computer and use it in GitHub Desktop.
Save lozadaOmr/f9c079ba82f49a2ece82 to your computer and use it in GitHub Desktop.

Laravel Session

For basic reference check Laravel Docs

http://laravel.com/docs/session


Creating New Item

Storing an item in session

Session::put('key', 'value');

Output will be an array with the key name 'key' and value of 'value'

{
  "key": "value"
}

Example

Session::put('id',1);

Output

{
  "id":1
}

Note : Use Session::put() only when adding an item in the session for the first time.


Adding item to Session

Push A Value Onto An Array Session Value

Session::push('user.teams', 'developers');

This will add the value of 'developers' to the key 'user.teams'


Retrieving an Item

Retrieving An Item From The Session

$value = Session::get('key');

Output

//display $value
return $value;

//output will be in JSON format (array)
{
  "key": "value"
}

Retrieving All Data From The Session

$data = Session::all();

This will get all data from the current session and store it to $data. You can try to return $data;, print_r($data); or var_dump($data); for checking all session data.


Determining If An Item Exists In The Session

if (Session::has('key'))
{
    //
}

This is useful when checking if value is already existing in the sessions array.


Removing An Item From The Session

Session::forget('key');

Use Case

In the Delivery Request, the added items are need to be temporary stored in the session's array, before it can be persisted to the database when the transaction is finalized. Note that this is just a bare run through and should not be used on production code.

Initial

On the initial state, the added-items array is not yet initialized, this will only happen when the user adds a new item. Knowing that, we then first need to check if added-items already exist.

if (Session::has('added-items')) 
{
    // do stuff here when added-items array exist
}
else
{
    // initialize added-items here
}

The code for initializing the added-items array is as follow.

Session::put('added-items', [
    0 => [
        'item_id'       => $id,
        'item_name'     => $new_item->item_name,
        'item_quantity' => Input::get('item_quantity')  
    ]
]);	

Looking at the code above, we've done some modifications. We created a added-items on the session's array. But instead of just a simple key and value. We declared its value as another array, not only that but value initialized as 0 contains yet another array which now contains the actual value.

Of course the obvious next step is passing these values from controller into the view.

added-items array visualized

"added-items": [
    {
        "item_id"      : 1,
        "item_name"    : "Epson Printer",
        "item_quantity": 99
    }
]

Getting the added-items

$added_items = Session::get('added-items');

Then you can just pass $added_items into the view using dymanic operator with()

return View::make('delivery-requests/create')->with('added_items',$added_items);

Now you can access the $added_items variable from the within the view


Additional Items

Now what if the added-items already exist and we need to make add new items to the array not create a new one. We Make use of Session::push() and use some logic, because simply pushing values to an array would create new arrays what if we wanted to update an existing array.

Array Manipulation

Since there are no way to manipulate session arrays directly we need to extract them. NOTE this is still a basic run through, refer to codes on the repo.

  • This commit shows basic ways to add items in a session array

NOTE:

codes below are annotated from top to bottom of DeliveryRequestController on line 45

Step 1

dump the new items into the array

Session::push('added-items', [
	'item_id' => $id,
	'item_name' => $new_item->item_name,
	'item_quantity' => Input::get('item_quantity')
]);

Step 2

store everything in a variable

$array = Session::get('added-items');

Step 3

create an empty array to store changed items

$total = array();

Step 4

Loop through the added-items array we passed on to the variable $array and add the new item_quantity to the total

foreach ($array as $key => $value) 
{
    $id = $value['item_id'];
    $quantity = $value['item_quantity'];
    
    if (!isset($total[$id])) 
    {
    	$total[$id] = 0;
    }
    
    $total[$id] += $quantity;
}

Step 5

Convert the contents of $total into the actual added-items array, we will use $items as placeholder of the actual new items

$items = array();

foreach($total as $item_id => $item_quantity) 
{
	$new_item = Item::find($item_id);
	$items[] = array(
		'item_id' => $item_id,
		'item_name' => $new_item->item_name,
		'item_quantity' => $item_quantity
		);
}

Take note of the $items[] is different with simply using $items. As arrays are not covered here check for the difference yourselves

Step 6

Since all new items are added to the $items array, now we push it to the added-items sessions array

Session::put('added-items', $items);

Tip

Check the contents of session array

Route::get('session',function()
{
    $data = Session::all();
    return $data;
}); 

Clear a 'key' in session array

Route::get('destroy', function()
{
    if (Session::has('added-items')) 
    {
	    Session::forget('added-items');
    }
    return Redirect::to('delivery-requests/create');
});

Flush all sessions array

Route::get('flush', function()
{
    Session::flush();
    return Redirect::intended('delivery-requests/create');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment