5

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.

1

5 Answers 5

23

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Perfect answer. It's worked for me. Now I can set user profile information in session correctly
This works but the session was not persistent for example user closes the browser and re-opens the page I had to use Middleware like this example mydnic.be/post/…
@JoelDavey app/config/session.php 'lifetime' => 43200, // 30 days 'expire_on_close' => false,
@shawn-lindstrom Tried to replicate your SetUserSession example, but Login event not being caught upon User Login. Do i need to register the Auth\Event\Login in the EventServiceProvider or should it work as above with nothing extra? Ty
@Greenie it is necessary to register the Listener in EventServiceProvider, at least when working in 6.x. Strange since the docs seem to indicate discovery should be automatic.
4

Laravel fires an event when a new login is made to the application. When an event fires you may add a listener for it, then add a session . This is the content of a listener I made.

<?php

namespace App\Listeners\Auth;

 use Illuminate\Auth\Events\Login;
 use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class UserLoggedIn
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }


    public function handle(Login $event)
    {

        if ($event->user->hasRole('subsidiary_admin')) {



            \Session::put('subsidiary_admin', $event->user->subsidiaryBoUser->subsidiary_id);
            \Session::put('subsidiary', $event->user->subsidiaryBoUser->subsidiary);



        }






    }
}

and I register it on the eventServiceProvider like this

 'Illuminate\Auth\Events\Login' => [
            'App\Listeners\Auth\UserLoggedIn',
        ],

Comments

3

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.

1 Comment

That's just how you would get data, but the question asks how to store data in a session. Can you edit your answer to include that?
1

You can store data in the session using two different methods either a Request instance or using the global helper/function provided.

Request Instance

public function methodA(Request $request) {
    $request->session()->put('KEY', 'VALUE');
}

Global Helper

public function methodB() {
    session(['key' => 'value']);
}

You can find more details on both methods in the documentation.

Comments

0

Here's what I am doing:

I have this on my helper file:

\App\Helpers\helpers.php:

function signedUser()
{
  return [
    'id'           => Auth::id(),
    'group_id'     => Auth::user()->group_id,
    'group_name'   => Auth::user()->group->name,
    'avatar'       => Auth::user()->avatar,
    'first_name'   => Auth::user()->first_name,
    'full_name'    => Auth::user()->full_name,
  ];
}

On my User Model:

public function group()
{
  return $this->belongsTo('App\Models\Group');
}

public function getFullNameAttribute()
{
   $full_name = ucfirst($this->first_name) . ' ' . ucfirst($this->middle_name[0]) . '. ' . ucfirst($this->last_name);

   return $full_name;
}

Then I can accessed the variables on both controllers and blade files like so:

dump(signedUser()['full_name']);

{{ signedUser()['full_name'] }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.