Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set Session Variable when User Login in Laravel

Invoice app development is going on using Laravel. I store date and amount format for every users in settings table.

When user login to their account how to set Session variable? Please give any suggestions. I am using Laravel 5.3.

like image 336
Karthik Avatar asked Feb 21 '17 06:02

Karthik


2 Answers

Of course the docs tell us how to store session data*, but they don't address the OP's question regarding storing session data at login. You have a couple options but I think the clearest way is to override the AuthenticatesUsers trait's authenticated method.

Add the override to your LoginController:

/**
 * The user has been authenticated.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  mixed  $user
 * @return mixed
 */
protected function authenticated(Request $request, $user)
{
    $this->setUserSession($user);
}

Then you can set your session up as:

protected function setUserSession($user)
{
    session(
        [
            'last_invoiced_at' => $user->settings->last_invoiced_at,
            'total_amount_due' => $user->settings->total_amount_due
        ]
    );
}

If you want to be a bit more clever you can create a listener for the Login or Authenticated events and set up the session when one of those events* fires.

Create a listener such as SetUpUserSession:

<?php

namespace app\Listeners;

use Illuminate\Auth\Events\Login;

class SetUserSession
{
    /**
     * @param  Login $event
     * @return void
     */
    public function handle(Login $event)
    {
        session(
            [
                'last_invoiced_at' => $event->user->settings->last_invoiced_at, 
                'total_amount_due' => $event->user->settings->total_amount_due
            ]
        );
    }
}

*Links go to 5.4 but this hasn't changed from 5.3.

like image 200
Shawn Lindstrom Avatar answered Oct 10 '22 10:10

Shawn Lindstrom


I've used the Auth class to manage user data, like this:

public function index(){   
  $user_id = Auth::user()->id;  
}

But you have to add 'use Auth;' before class declaration. Then you can add any data to session variable.

like image 33
MánuelPa Avatar answered Oct 10 '22 10:10

MánuelPa