简体   繁体   中英

Should I better use session() or collect() helper function in Laravel 5.7?

I have stored my array data in the session as following.

session(['my_key' => ['car' => 123, 'motor' => 45, 'boat' => 678]]);

To get the keys I could do the following:

$car_key = session('my_key.car');
$motor_key = session('my_key.motor');
$boat_key = session('my_key.boat');

Or I can do the following:

$my_keys = session('my_key');

$car_key = collect($my_keys)->get('car');
$motor_key = collect($my_keys)->get('motor');
$boat_key = collect($my_keys)->get('boat');

I don't know how session() and collect()->get() function handle array . Is one approach better than another in this case? Or it does not matter that much, even the session stores array with large data?

collect() helper is used to create a collection. In you second way you create three different collections, containg the same collection data. And then you get the data, by the key from each collection. The colde seems to be redudant and is not used as it should be used.

Use the session() helper

It depends.

If you want to use methods that are only available on collections then that would be a perfectly valid way to do so. A simpler approach would be to use:

$myCollection = collect(session('my_key'));

That way you can just use $myCollection->get('car') etc, rather than creating multiple collections.

If however you just want to retrieve the value and are happy with an array you can just use the session() helper and return the data as normal.

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