how to session()->forget('cart') for another user in laravel? - laravel

my session driver is set to database,
.env => SESSION_DRIVER=database
I have made a model for session and I access to a session of another user by user_id like this :
use App\Models\Session;
$payload = Session::where('user_id', $request->user_id)->pluck('payload');
$payload = unserialize(base64_decode($payload));
if (!isset($payload['cart'])) {
dd($payload['cart']);
}
now I want to session()->forget('cart') of that specific user not the current user, but the payload field is decode by base64 and serialized.
how to do that?
thanks

I tried a few things and by changing the id it works :
// Get the store from laravel (encrypted or not)
$store = session()->getDrivers()['database'];
// Change the id
$store->setId($id);
// Start the session
$store->start();
// Remove the item
$store->pull('cart');
// Save the session in database
$store->save();
i don't think it's something that laravel support, so this might break in the future

Yes I found it.
the problem is to displacement of serialize() and base64_encode() after unset($payload['cart']) like this:
use App\Models\Session;
$session = Session::where('user_id', $request->user_id)->first();
$payload = unserialize(base64_decode($session->payload));
if (!isset($payload['cart'])){
unset($payload['cart']);
}
$session->payload = base64_encode(serialize($payload));
$session->save();

Related

Save complete model in session - Codeigniter

I want to save complete model in session, so I can use data easily in entire application.
After successful login in application I am saving model in session and session save in database in ci_session table.
Code I tried:
$loginSuccess = $this->login_model->doLogin($username, $password);
if($loginSuccess) {
$this->login_model->initialize(); // this will set value in private variable
$serializelogin = serialize($this->login_model);
$this->session->set_userdata('userprofile', $serializelogin);
}
This code gives me an error:
Error Number: 2006
MySQL server has gone away
Update: I change user_data column of table ci_session from text to longtext
U need to start by creating a session.
//Destroy old session
$this->session->sess_destroy();
//Create a fresh, brand new session
$this->session->sess_create();
//Set session data
$this->session->set_userdata($row);
Basically $row is an array.
$row = $serializelogin->row_array();
or
$this->session->set_userdata(array('active_flag' => false, 'active_status' => 0));
make sure the data which has been returned from the model is in row_array format.

How to Check if Session is set in Laravel 5.7

<?php
$request = request();
// if (empty($request)) return false; .// That does not work
$loggedUserAccessGroups = $request->session()->get('loggedUserAccessGroups');
$logged_user_ip = $request->session()->get('logged_user_ip');
In my Laravel 5.7 application, I want to check if the user has the right access level in the session. It works ok but I made automatic tests and got the error:
local.ERROR: Session store not set on request.
I added checks to see if the session is set and it fails to return false.
Which is the correct way? Thanks!
You may also use the global session PHP function to retrieve and store data in the session as outlined here:
// Retrieve a piece of data from the session with the global session helper...
$loggedUserAccessGroups = session('loggedUserAccessGroups');
$logged_user_ip = session('logged_user_ip');
// Store a piece of data in the session...
session(['key' => 'value']);
For more information look at the section of The Global Session Helper in the official documentation.

how to hash a password laravel 5.2 model create

I'm creating admin user via model and it saving record successfully but password is not being hashed as follows:
$request->password = bcrypt($request->input('password'));
Admin::create($request->except('_token'));
you can not modify $request properties like that.
Give it a try:
$input = $request->except('_token');
$input['password'] = bcrypt($input['password']);
Admin::create($input);
OR, handle it in your Admin Model
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
Then you can
Admin::create($request->except('_token'));
Take a look at Laravel's Hashing documentation. It shows that you should be hashing any strings like so:
Hash::make($request->newPassword)
However looking at your code, i'd say this issue is actually the fact you're trying to modify the request $request->password, this is not going to work how you expect. Look at your Admin model class and see what the code is expecting, perhaps this is already in built if you pass the correct arguments.

Laravel How to store extra data/value in session Laravel

I'm using default auth() in laravel login (email & password)
Now i try to take input from the user in text field like (Age or City)
Now i want to store (Age/City) in my session.
Help me
You can use session() helper:
session('age', 18); // saves age into session
$age = session('age')`; // gets age from session
Update
If you want to save Age and City after user registration, you should store this data in a DB, not in a session. You can add some fileds in create method of app\Http\Controllers\Auth\AuthController.php
You can use
Session::put('key', 'value');
To get key from Session use
Session::get('key');
You can use the session() helper function as #Alexey Mezenin answer.
Laravel Session Documentation
Ok let me enlighten you. if you want to store it in session do it this way.
session('country', $user->country); // save
$country = session('country')`; // retrieve
But that is not the way we do in Laravel like frameworks, it uses models
once the user is authenticated each time when we refresh the page, application looks for the database users table whether the user exists in the table. the authenticated user model is a user model too. so through it we can extract any column. first thing is add extra fields to the User class(Model) $fillable array.
so it would look something like this.
User.php
protected $fillable = ['username', 'password', 'remember_token', 'country'];
so after simply logging in with user name and password in anywhere just use Request class or Auth facade. Facades are not too recommended so here for your good as a new one i would just say how to use Request. Suppose you want to retrieve your Authenticated user country inside TestController.php here is how it could be used in the methods.
TestController.php
use Illuminate\Http\Request;
public function testMethod(Request $request)
{
$someCountry = $request->user()->country; //gets the logged in user country
dd($someCountry); //dd is die and dump, could be used for debugging purposes like var_dump() method
}
Using Request
public function ControllerName (Request $request){
$request->session()->put('session_age', $age);
}
Get session_age
$get_session_age = $request->session()->get('session_age');
Using Session
public function ControllerName (){
Session::put('age',$age);
}
Get the session
$session_age = Session::get('age');
Don't forget to define Session or Request in your controller!!!
use App\Http\Requests;
use Session;
To work with session in your controller you need to include session first in your controller
use Session;
After that for store data in session. There is several ways to do it. I prefer this one (in controller)
session()->put('key',$value);
To display session data in your View you can do it like this
#if(Session::has('key'))
I'v got session data
#else
I don't have session data
#endif
To get session data in your Controller you can do it like this
session()->get('key')
//or
session()->get('key','defaul_value_if_session_dont_exist')
When you are done with your data in session you can delete it like this (in controller)
session()->forget('key');
All this basic usage of session is well documented in official Laravel documentation here.
Hope it helps you

How to "Refresh" the User object in Laravel?

In Laravel you can do this:
$user = Auth::user();
Problem is, if I do changes on items on that object, it will give me what was there before my changes. How do I refresh the object to get the latest values? I.e. To force it to get the latest values from the DB?
You can update the cache object like this.
Auth::setUser($user);
for Example
$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();
Auth::setUser($user);
log::error(Auth::user()->name)); // Will be 'NEW Name'
[This answer is more appropriate for newer versions of Laravel (namely Laravel 5)]
On the first call of Auth::user(), it will fetch the results from the database and store it in a variable.
But on subsequent calls it will fetch the results from the variable.
This is seen from the following code in the framemwork:
public function user()
{
...
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
...
}
Now if we make changes on the model, the changes will automatically be reflected on the object. It will NOT contain the old values. Therefore there is usually no need to re-fetch the data from the database.
However, there are certain rare circumstances where re-fetching the data from the database would be useful (e.g. making sure the database applies it's default values, or if changes have been made to the model by another request). To do this run the fresh() method like so:
Auth::user()->fresh()
Laravel does do that for you, HOWEVER, you will not see that update reflected in Auth::user() during that same request. From /Illuminate/Auth/Guard.php (located just above the code that Antonio mentions in his answer):
// If we have already retrieved the user for the current request we can just
// return it back immediately. We do not want to pull the user data every
// request into the method because that would tremendously slow an app.
if ( ! is_null($this->user))
{
return $this->user;
}
So if you were trying to change the users name from 'Old Name' to 'New Name':
$user = User::find(Auth::user()->id);
$user->name = 'New Name';
$user->save();
And later in the same request you try getting the name by checking Auth::user()->name, its going to give you 'Old Name'
log::error(Auth::user()->name)); // Will be 'Old Name'
A little late to the party, but this worked for me:
Auth::user()->update(array('name' => 'NewName'));
Laravel already does that for you. Every time you do Auth::user(), Laravel does
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
$user = null;
if ( ! is_null($id))
{
$user = $this->provider->retrieveByID($id);
}
It nulls the current user and if it is logged, retrieve it again using the logged id stored in the session.
If it's not working as it should, you have something else in your code, which we are not seeing here, caching that user for you.

Resources