laravel get session data and order by latest - laravel

I'm working on a session data with Laravel and I can store sessions into a variable and retrieving the whole data. But my problem is I want to order the session to the latest 5 id's from the session stored.
Storing session
session()->push('products.recently_viewed', $product->getKey());
Retrieving session
$ids = session()->get('products.recently_viewed');
$recently_viewed = Product::whereIn('id', $ids)->get();
The retrieving is working fine, I only want to get the latest 5 id's from the session products.recently_viewed
e.g.
data from sessions
[1,3,7,6,8,9,11,2]
data I want to get
[2,11,9,8,6]

You need array_slice and array_reverse
$items = array_reverse(array_slice($yourSessionArray, -5));
-5 means "start at five elements before the end of the array".
the reverse will reverse the order of the array so the last is first.

Related

What is the different between laravel PLUCK and SELECT

I found that laravel 'pluck' return an plain array and 'select' return an object. Can anyone explain it to me have any other different between two this?
thank you.
Pluck is a Laravel Collections method used to extract certain values from the collection. You might often want to extract certain data from the collection i.e Eloquent collection.
While Select is a normal selection of either multi or specific columns. They are
By using Pluck you only ask to return necessary fields, but with get you will pull all columns. Also select does the same & the difference here is between the returning result. Using pluck cause returning the final result as an array with pair of given arguments, but select return an array (or object) which every single child contain one row.
$name = DB::table('users')->where('name', 'John')->pluck('name');
Select
EX : DB::table('users')->select('id', 'name', 'email)
Select is a method sent to the database that Laravel will translate as
SELECT id, name, email FROM users
This will select the data of the columns you asked and nothing else. It allows you to be more efficient with your request by only asking the required data. Take the example above and image that the user is a Facebook user. It has a ton of data on it, plus relations to other tables. If you just want to display the name, email and a link to the user profile, doing this request!
For more info and knowing more about the expected response visit : https://laravel.com/docs/9.x/queries#select-statements
Pluck
EX:
$users = DB::table('users')->where('roles', '=', 'admin')
$emails = $users->pluck('email')
The Pluck method retrieves the values in a collection that you already got from the Database and that is now a Laravel Collection. This allows you to create an array of the plucked data, but will not improve the performance of your request, as in the Example above, the $users would hold all data of all the admin users.
Since it does not improve performance, what good is it then ?
The pluck would be useful for example to separate some datas in different variables depending on where. You might need the users data for some stuffs, but also want to display a quick list of all emails together.
For more info about the pluck method and understand how to create a keyed array from a second column, visit the docs here: https://laravel.com/docs/9.x/collections#method-pluck
Pluck function normally used to pull a single column from the collection or with 2 columns as key, value pairs, which is always be a single dimension array.
Select will return all of the columns you specified for an entity in a 2 dimensional array, like array of selected values in an array.
Note: Pluck function is a collection function which happens after the data is fetched. Select is a query builder function that builds query to perform in the database server.
Actually select is used inside DB queries, which can affect the performance by limiting the pulled columns. However, Pluck is Laravel Collection's method, so you can use pluck after you pull the data from DB.

how to store an object model into an array in the session and keep the relations updated with database in laravel?

I am trying to store an array of model objects ( carts ) in the session but the problem is when I print out these carts their relationships are not updated with the database
There are 2 ways of approaching this problem.
1 - store only the ID
If you store only the id of the data in the session, when you get the model back from the ID, Eloquent fetches all the relation properly.
2 - Serialize the model in the session
Laravel and Eloquent provides a way to serialize objects and particularly models : https://laravel.com/docs/8.x/eloquent-serialization
A serialized model is a JSON string that you can store in session.
But you need to rehydrate the model with JSON data when you get it back from the session so in the end it's not easier than storing the id and reloading the model from the DB.
PS:
You can also take a look at model caching if you need to store instance of a model that is rarely updated to save database access:
https://laravel-news.com/laravel-model-caching

magento 2 store manager always returns default store id

I'm implementing module which have to store different data for all stores, so i need get current store id and set id to db with new records. I'm trying get store id this way
$storeId = $this->_storeManager->getStore()->getId();
But when i change scope to another store (which has id "2") then $storeId still has value "1" (default store). I see that last param in my url has changed
store/2/
but in code has returned default store id. Any idea what causing that problem?
The problem is with your assumption that when changing the configuration scope you also change the the backend scope, which is not so. See the following issue in github for a solution to your problem:
https://github.com/magento/magento2/issues/9741.
tl;dr: get the store id from request params: $this->_request->getParam('store', 0)

How to keep session id after login in Laravel 5.1

I been using my session id to identify all the items that are added to a shopping cart temporary items table.
What I didn't know is that once the user login into the system the session id changes so I can't query the temporary items table anymore as there is no products containing the new session id value.
I am using file session driver and I was thinking to use db sessions but I think it will be exactly the same.
Any ideas on how to keep the session id after login?
Instead of using user's session_id you can store the cart items in a separate session key.
Like so -
Session::put('cart.items.0', $item_id);
Now you can access it as -
$cart = Session::get('cart');
Not exactly what you asked for, but to me this seems like a better way.

codeigniter session save to database keep updating many times

I have a question. I'm using latest version of CI.
I have currently enabled session to use the database, but there is only one problem with how it works since it tends to update the database every time you update your session.
Is there a way to fix that so that session would only update the database once before it destructs?!
I currently have around 9 update requests from one CI session only :) ! so any help would be lovely.
a simple Code example, my proccess is much more complicated than this, but just for demonstration purpose
Controller/auth [include post with true login]
function login(){
$trial=$this->user->attempt($this->input->post('user'),$this->input->post('pass'));
if($trial){
//1st update query
$this->session->set_userdata('user',$trial);
//Start intializing user
//2nd update query
$this->load->model('relations');//constructer will load user friends and save them to $this->session->set_userdata('relations',$rel);
//3rd update query
$this->load->model('settings');//construtor will load user settings and save them to settings
}
}
Above code will create 3 update request all targeted to update field userdata = current session.
my point is there is no need to update db every time we add something to session, its already saved in $_SESSION, so keep it there , and keep manipulating $_SESSION till end,
only updating user_data once at the end of all runtime -destructor- with the end result session is enough to save session to db.
please note that CI loads session from session using select * from ci_session (first request in picture) and then it just keep updating session repeatedly and pointless since it will not select it again during runtime !
so why not just LOAD it once session library is loaded. and save it just before it destruct. thats what im trying to accomplish.
Thanks
I have found a solution for this, get the existing user data from the session by using following code
$userdata = $this->session->all_userdata();
$userdata['fname'] = 'John';
$userdata['lname'] = 'Mulharn';
$userdata['email'] = 'Mulharn#john.com';
$this->session->set_userdata($userdata);
All this happens in 1 transaction instead of 3 database transaction.
Hope that helps.
A session may be updated by passing an array with all of the values, rather than doing them one at a time. Have another look in the Users' Guide

Resources