Home > Software engineering >  Change global variable in usage every time the user logins in Laravel 8
Change global variable in usage every time the user logins in Laravel 8

Time:04-13

One of the functionalities that the website I'm building requires is the ability to change a value from the login view, and that value will show in every other module/view on the entire site. For this, I made a select dropdown to choose said variable, and supposedly that variable must be shown everywhere the user goes.

enter image description here

To make a global variable in Laravel, I need to create a file in the folder /config and call the file with the variable in the controller I need. I already call an example variable to show it at the beginning of the website.

config_ciclos.php

<?php
 return [
'variables' => [
    'ciclo1' => '20-21',
    'ciclo2' => '21-22',
    'ciclo3' => '22-23'
 ],
];

HomeController

public function index()
{
    $ciclo = config('config_ciclo.variables.ciclo1');
    $auth = Auth::id();
    if ($auth != null) {
        return view('home', compact('ciclo'));
    } else {
        return redirect('/');
    }
}

The only thing that eludes me is how can I make a variable that I can pass every time a user logs in that dictates what global variable is in use?

I wondered if I could create a variable inside the request on login similar to a user session. Then, I could call every controller to select the global variable I'm using, which expires after the session's time limit. However, I don't know how to do that. The only thing I'm sure of is that maybe I could use the file AuthenticatesUsers.php because all the methods of auth and login are there.

CodePudding user response:

You can use Laravel Auth Controller, you can put data to your session or you can use event/listener approach.

LoginController.php

// Store a piece of data in the session...
session(['config_ciclo' => config('config_ciclo.variables.ciclo1')]);

and get value in your view like:

$value = session('config_ciclo);
  • Related