How can I persist Laravel session data using Inertia Vue? - laravel

I'm having trouble updating session values using Inertia.js. The behavior I was expecting was that the redirect to 'Home' would happen only once. Once the session gets cleared, any page reloads would go into 'Nok.' But that's not what happens. The $request->session()->forget(['ok']); is not persisted and always falls back to 'Home'. How do I get the expected behavior?
Example
public function home(Request $request)
{
$ok = $request->getSession()->get('ok', null);
if ($ok) {
$request->session()->forget(['ok']);
return Inertia::render('Home', [...]);
} else {
return Inertia::render('Nok', [...]);
}
}

Related

refresh page after updated model - Laravel

I want to refresh current page after any user update
I'm trying to do something like that in User Model :
public static function boot()
{
self::updated(function ($model) {
return back(); //or redirect(Request::url())
});
}
but it wasn't working.
How can I refresh the page if any user updated
In general, the model event functions creating/created/updating/updating/saved/saving should only ever return false or nothing (void). Returning false in for instance updating (that is: before the model is persisted in the database) cancels the model update (this works for all propagating events, see https://laravel.com/docs/9.x/events#stopping-the-propagation-of-an-event).
To "refresh" the current page after a user update, you have to be more specific about what you require. The back() function that you use (or the aliases redirect()->back() or even app('redirect')->back()) is (to my knowledge) to be used in controllers and it uses the Referer header or a property in the user's session to determine to which page to send the client to. This is most often used with validation errors, so that you can send the user back to the page they came from along with any possible validation error messages.
Using back() (or any other request completions like return response()->json('mydata')) inside events is wrong and it doesn't even work since the result of such events is not being used to complete the request. The only valid thing you "could" do is to try validation inside an event, which in turn could throw ValidationExceptions and is therefore automatically handled.
What you should do is use the controller method that actually handles the request that updates the user:
// UserController.php
/** (PUT) Update a user */
public function update(Request $request, User $user)
{
if($user->update($this->validate($request, [/* validations */])) {
return redirect()->back();
// or even be explicit and use `return redirect()->route('users.show', $user);`
}
// `update()` returned false, meaning one of the model events returned `false`
// (there is no exception thrown here).
session()->flash('alert-info', 'Something went wrong');
return redirect()->back();
}

Changes in Controller not reflecting showing previous return value

O make change in Controller but it is not effecting it is returning previous changed value not new.
I make many different kind but it is showing same first value which was returned.
I want to return new value from controller
//------------Logout---------------
public function logoutme() {
if (Session::has('RedPachUID')) {
Session::forget('RedPachUID');
return "yes";
}
}
New Function
//------------Logout---------------
public function logoutme() {
if (Session::has('RedPachUID')) {
Session::forget('RedPachUID');
return "No";
}
}
it was happening because I was using anchor tag when i used form to logout it helps me
here is complete solution logout function not invalidating session

Session value get deleted on page refresh in ci

I have a login function. When I login, the session gets saved. But when I refresh the page or redirect to another function, then the session (userdata) is shown blank. I have loaded the session library in autoload, but the userdata is deleted after every page refresh.
Here is my code.
public function index () {
$user = $this->input->post('user');
// after successful user checking
$this->session->set_userdata('user', $user);
// when I print session here,
print_r($this->session->all_userdata());
// session user gets print
}
But when I redirect to a function (suppose 'test'), then no any session is shown.
public function test() {
print_r($this->session->all_userdata());
die;
}
When you read the post value with $this->input->post('user'); and there isn't any post the function returns null and save this in the user value.
You have to check before setting.
if ($this->input->post('user')) {
$this->session->set_userdata('username', $this->input->post('user'));
}
I solved the problem. Actually, accidentally I had destroyed the session at the beginning of the code. So, my session was all destroyed. I removed the code and it's working fine.

Codeigniter session clear on login

I save preferences of anonymous user in sessions.The issue is that when user did login,I have to clear previous sessions and start new one(for security reasons).
It seems if I destroy session, then login function would do logout! Even though I use set_userdata after sess_destroy it cannot do login (maybe session after destruction becomes unusable).
Using unset acts only on a few specified sessions.Is there any way to clear all sessions of the user without such a problem?
public function login()
{
if($this->session->userdata('id'))
redirect($this->config->base_url());
if($_POST)
{
...
$user=...
if($user)
{
$this->session->sess_destroy();
$this->session->set_userdata('id',$user['id']);
....
}
else
{
....
}
}
$this->load->view('...');
}
Try reinitializing the session library after you run sess_destroy().
$this->session->sess_destroy();
$this->load->library('session');
$this->session->set_userdata('id',$user['id']);
Update:
It appears that CI does not have a native function to clear the session without damaging it for the rest of the script runtime.
However, searching for the root cause yielded a manual answer.
function unset_only() {
$user_data = $this->session->all_userdata();
foreach ($user_data as $key => $value) {
if ($key != 'session_id' && $key != 'ip_address' && $key != 'user_agent' && $key != 'last_activity') {
$this->session->unset_userdata($key);
}
}
}
do not use sess_destroy unless you are planning to redirect back again on the same url.
just use
$this->session->set_userdata('id','')
or you could create an array of the sessions you want to destroy and on its value just add a null sample
$test = array('session_id'=>'','session_id2'=>'');
$this->session->set_userdata($test);
this will make the session with names session_id and session_id2 NULL or FALSE
because when you called sess_destroy() it destroys all the session the app is using. even if you try to add another session after calling it it will not add since there are no active sessions and That's why it will not work. Tried it many times, it will only work if you refresh or redirect back to the controller/method so that a new session will be created. That's how session in CI works, i don't know correct me if i'm wrong.

CakePHP 2 AJAX redirections

I'm using AJAX in my web-app stuffs like search but if the user has been logged out, the ajax function return nothing because the redirection (from the action 'search' to the action 'login') has not been handled correctly.
Is it possible to redeclare the method 'redirect' in AppController to render the right action when a redirect hapend in an AJAX call ?
Thank you,
Sébastien
I think your best bet would be to setup you ajax to call to respond correctly to an invalid response. As it seems to be an important part of your app I would pass a 'loggedin' variable with every ajax request, so the client can tell as soon as the user has been logged out.
Update
In the case you want to keep a user logged in, you simply have to put the logged in/cookie check in something like your AppController::beforeFilter() that gets run with every request. for example:
public function beforeFilter() {
if($this->Auth->user() {
// USer is logged in, it's all gravy
} else {
// User is not logged in, try to log them in
$userData = $this->Cookie->read('User');
if(!empty($userData)) {
// Function that grabs info from cookie and logs in user
}
}
}
This way there will be no redirect as the user will be logged in as long as they have a cookie.
Another approach would be to allow everyone access to the Ajax function:
public function beforeFilter() {
$this->Auth->allow(array('my_ajax_method'));
}
And then check the user is authenticated in the method itself:
public function my_ajax_method() {
if (!$this->Auth->user()) {
//user not authenticated
$result = "requires auth";
}
else {
// use is authenticated
// do stuff
$result = 'result of stuff';
}
$this->set(compact('result'));
}
You will need to check the result of the ajax call in your javascript and act accordingly.

Resources