I would like to set a variable in the session using laravel this way
Session::set('variableName')=$value;
but the problem is that I don't know where to put this code, 'cause I would like to set it for one time (when the guest visite the home page or any other page)?
The main idea is to use a global variable to use it in all application controllers, I heared about something related to configuration variables but I'm not sure if it will be a good Idea to use config variables or only the session?
Thanks
The correct syntax for this is:
Session::set('variableName', $value);
For Laravel 5.4 and later, the correct method to use is put:
Session::put('variableName', $value);
To get the variable, you would use:
Session::get('variableName');
If you need to set it once, I'd figure out when exactly you want it set and use Events to do it.
For example, if you want to set it when someone logs in, you'd use:
Event::listen('auth.login', function() {
Session::set('variableName', $value);
});
I think your question ultimately can be boiled down to this:
Where can I set a long-lived value that is accessible globally in my application?
The obvious answer is that it depends. What it depends on are a couple of factors:
Will the value ever be different, or is it going to be the same for everybody?
How long exactly is long-lived? (Forever? A Day? One browsing 'session'?)
Config
If the value is the same for everyone and will seldom change, the best place to probably put it is in a configuration file somewhere underneath app/config, e.g. app/config/companyname.php:
<?php
return [
'somevalue' => 10,
];
You could access this value from anywhere in your application via Config::get('companyname.somevalue')
Session
If the value you are intending to store is going to be different for each user, the most logical place to put it is in Session. This is what you allude to in your question, but you are using incorrect syntax. The correct syntax to store a variable in Session is:
Session::put('somekey', 'somevalue');
The correct syntax to retrieve it back out later is:
Session::get('somekey');
As far as when to perform these operations, that's a little up to you. I would probably choose a route filter if on Laravel 4.x or Middleware if using Laravel 5. Below is an example of using a route filter that leverages another class to actually come up with the value:
// File: ValueMaker.php (saved in some folder that can be autoloaded)
class ValueMaker
{
public function makeValue()
{
return 42;
}
}
// File: app/filters.php is probably the best place
Route::filter('set_value', function() {
$valueMaker = app()->make('ValueMaker');
Session::put('somevalue', $valueMaker->makeValue());
});
// File: app/routes.php
Route::group(['before' => 'set_value'], function() {
// Value has already been 'made' by this point.
return View::make('view')
->with('value', Session::get('somevalue'))
;
});
In Laravel 5.6, you will need to set it as:
session(['variableName' => $value]);
To retrieve it, is as simple as:
$variableName = session('variableName');
For example, To store data in the session, you will typically use the putmethod or the session helper:
// Via a request instance...
$request->session()->put('key', 'value');
or
// Via the global helper...
session(['key' => 'value']);
for retrieving an item from the session, you can use get :
$value = $request->session()->get('key', 'default value');
or global session helper :
$value = session('key', 'default value');
To determine if an item is present in the session, you may use the has method:
if ($request->session()->has('users')) {
//
}
in Laravel 5.4
use this method:
Session::put('variableName', $value);
To add to the above answers, ensure you define your function like this:
public function functionName(Request $request) {
//
}
Note the "(Request $request)", now set a session like this:
$request->session()->put('key', 'value');
And retrieve the session in this way:
$data = $request->session()->get('key');
To erase the session try this:
$request->session()->forget('key');
or
$request->session()->flush();
You can try
Session::put('variable_Name', "Your Data Save Successfully !");
Session::get('variable_Name');
In Laravel 6.x
// Retrieve a piece of data from the session...
$value = session('key');
// Specifying a default value...
$value = session('key', 'default');
// Store a piece of data in the session...
session(['key' => 'value']);
https://laravel.com/docs/6.x/session
If you want persistence sessions,
Method 1: use session()->save() or Session::save()
session(['key' => 'value']);
//or
session()->put('key', 'value');
//then
session()->save();
echo session('key');
Method 2: Move bellow line from protected $middlewareGroups of app\Http\Kernel.php to protected $middleware array as first line
\Illuminate\Session\Middleware\StartSession::class,
Make sure the storage directory has write permission
chmod -R a+rw storage/
Don't use dd() to verify session, use print_r()
to set session you can try this:
$request->session()->put('key','value');
also to get session data you can try this:
$request->session()->get('key');
If you want to get all session data:
$request->session()->all();
Related
I want to add a session of warning like this at my Controller method:
return view('panel.step3' , compact('factor' , 'showStep') )->with('warning' , 'test !');
And then on view panel.step3, I have added this: #dd(session('warning'))
But it says: NULL
So what is going wrong here ? How can I properly add my session ?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.
The with() method performs differently based on where you chain it. For a view():
return view('view.name')->with('variable', 'value');
The 'variable' will be available as a variable, $variable, and not via the session session()->get('variable').
When you use with() on a redirect():
return redirect()->route('route.name')->with('variable', 'value');
Then the 'variable' is available via session(), and not as $variable.
This is due to the request life-cycle; for view(), it's a single chain of calls, so setting a variable is acceptable. For redirect(), it needs to perform a brand new request, and variable persistence across calls is done via session logic.
If you wish to use session() with view(), simply do a flash():
session()->flash('variable', 'value');
return view('view.name');
In this case, session()->get('variable') is valid, while $variable is not.
Because you just render the view with data, not redirect to another action, so you didn't put anything to session.
Is it right to get Session data in a store function and store them into db?
public function store(){
...
$idgroup = Session::get('invitation_userid')];
...
}
Or need a store function always a Request Object?
public function store(Request $request){
...
$idgroup = $request('idgroup');
...
}
In both functions is of course a validation part for the input data.
Both approaches are fine, but you should use them appropriately to your use case, I prefer to use the Request data. The main difference is that if u store that inside the Session it will be available application wide, while if u send inside Request it will be available inside the method only
This depends entirely on the context of what your controller is actually named, how this data is being used and why you are not using a database session driver in the first place if you want to do this.
You could simply use the database driver for the session:
https://laravel.com/docs/5.7/session#introduction
It also depends on what your controller is named if you strictly want to follow restful routes:
https://gist.github.com/alexpchin/09939db6f81d654af06b
To answer the second question you don't always need a Request object in your store action. Most of the time you won't even see a Request object because you are simply creating an entirely new resource.
The Global Session Helper
You may also use the global session PHP function to retrieve and store data in the session. When the session helper is called with a single, string argument, it will return the value of that session key. When the helper is called with an array of key / value pairs, those values will be stored in the session:
$value = session('key');
I'm using a package within my project and it stores a setting inside config/packagename
I would like to dynamically change this value inside the config file, this is how the file structure looks currently;
<?php
return [
'view_id' => '118754561',
'cache_lifetime_in_minutes' => 60 * 24,
];
I would like to change it to something like this -
'view_id' => Auth::user()->id,
Can you do this within the config file, or do you have to store some sort of variable to be updated later within a controller. Is there a way to place these variables in an env file and access these new variables from a controller?
This also is a generic solution to dynamically update your .env file (respective the individual key/value pairs)
Change the setting in your config/packagename like so:
return [
'view_id' => env('VIEW_ID', '118754561'),
etc...
]
Add an initial value into .env:
VIEW_ID=118754561
In an appropriate controller (e.g. AuthController), use the code below and call the function like this:
updateDotEnv('VIEW_ID', Auth::User()->id)
protected function updateDotEnv($key, $newValue, $delim='')
{
$path = base_path('.env');
// get old value from current env
$oldValue = env($key);
// was there any change?
if ($oldValue === $newValue) {
return;
}
// rewrite file content with changed data
if (file_exists($path)) {
// replace current value with new value
file_put_contents(
$path, str_replace(
$key.'='.$delim.$oldValue.$delim,
$key.'='.$delim.$newValue.$delim,
file_get_contents($path)
)
);
}
}
(The $delim parameter is needed if you want to make this function more generic in order to work with key=value pairs in .env where the value has to be enclosed in double quotes because they contain spaces).
Admittedly, this might not be a good solution if you have multiple users at the same time using this package in your project. So it depends on what you are using this package for.
NB: You need to make the function public of course if you plan to use it from other classes.
All configuration files of Laravel framework stored in the app/config directory.
so if we need to create custom configuration values it would be better to keep separate our custom configuration in custom file.
so we need to create custom file in app/config directory.
Laravel auto read this file as a config file and will auto manage it
In this topic we are working with custom configuration in laravel and get configuration value in controller or view.
Now i am going to explain how to create a custom config file in Laravel so that we can implement dynamic feature over to this.
create a file in app/config/custom.php which have config keys and value like:-
return array(
'my_val' => 'mysinglelue',
'my_arr_val' => array('1', '2', '3'),
);
Now need to get these config values in view/controller so we will use Config class get() method for this
Syntax:
echo Config::get('filename.arraykey');
where filename is the config file’s name, custom in our case, and key is the array key of the value you’re wanting to access.
In Our case it will be as:
echo Config::get('custom.my_val');
Create run time configuration in laravel :-
Configuration values which are set at run-time are will set for the current request, not be carried over to subsequent requests.
You can pass the dynamic values over here so that you can modify the config file dynamically over here using the isset() functions.
Like how the #Kundan roy as suggested using of the isset() the same condition applies here to. But this one is the alternative method that will work for the dynamic setting of the values in the config.
Config::set('custom.my_val', 'mysinglelue');
Hence by using this method you can create the dynamic config files based on the values that you need.
Since Laravel v5.2 you can dynamically set config values this way:
<?php
config(['app.timezone' => 'America/Chicago']);
$value = config('app.timezone');
echo $value;
// output: 'America/Chicago'
If you want to actually edit the config files (either config/packagename.php or .env) then you may follow matthiku's answer.
However, if I were you, I guess I'd rather want to configure this 3rd party package based on some value defined at runtime, instead of modifying any file (which by the way won't take effect until the next request, when the env values are read again).
So, in my opinion the cleanest way to do this is:
store your desired value in the config data:
config(['packagename.view_id' => Auth::user()->id]);
However, you may notice this probably won't work: the service provider which provides the service you need is often registered before the request is processed, that is, before your config change takes place. So you are still getting the service with old values config.
So, how could you have the service provider be called only when needed and not before (that is, after setting the new config value)? You could make it a deferred provider. Following your example of "spatie laravel-analytics", replace in config/app.php this line:
Spatie\Analytics\AnalyticsServiceProvider::class
with this one:
App\Providers\AnalyticsDeferredServiceProvider::class
and finally create the App\Providers\AnalyticsDeferredServiceProvider class, with:
:
<?php
namespace App\Providers;
use Spatie\Analytics\Analytics;
use Spatie\Analytics\AnalyticsServiceProvider;
class AnalyticsDeferredServiceProvider extends AnalyticsServiceProvider
{
protected $defer = true;
public function provides()
{
return [Analytics::class];
}
}
This way you can have the provider read the config values when you are about to instantiate the service, after you set any runtime config values.
Use this in controller when you need to change.
<?php
use Illuminate\Support\Facades\Config;
//[...]
$user_id = Auth::user()->id;
Config::set('view_id', $user_id );
You can do like this.
In your custom config file. Add the following code You can send your id dynamically from the query string.
'view_id' => isset($_REQUEST['view_id'])?$_REQUEST['view_id']:null,
To get view id
echo config('app.view_id'); // app is config file name
config(['packagename.view_id' => Auth::user()->id]);
Actually if you are that point of code which forces you to make the config values dynamic, then there should be something wrong with your code flow, as the use of config file is just for initializing required values - which should be defined before the app is loaded.
Making config values dynamic is a "BAD PRACTICE" in the world of coding.
So there is the following alternative for your problem.
Define value in .env file (optional)
VIEW_ID=your_view_id_here
Use value inside Controller
$auth_id = auth()->user()->id;
$view_id = env('VIEW_ID', $auth_id);
// If .env file doesn't contains 'VIEW_ID' it will take $auth_user as the view_id
Hope this helps you!
config::set() doesn't works for me in laravel 8. but I got best answer for Create or edit Config file
config(['YOUR-CONFIG.YOUR_KEY' => 'NEW_VALUE']);
$text = '<?php return ' . var_export(config('YOUR-CONFIG'), true) . ';';
file_put_contents(config_path('YOUR-CONFIG.php'), $text);
just try this way this works for me.
original answer you can see here
I use Gethebert (http://getherbert.com/) as plugin in wordpress. This one is having structure as Laravel framework.
Also it uses mostly same components as laravel used.
But my query is how to use its session.
In laravel i use,
Session::put('name','value'); //to Set Session Value
and
Session::get('name'); //to Get Session Value
But in Getherbert, I dont know the right way to use session.
Suggest me the right one....
Thank you !
You can always use standard PHP $_SESSION:
http://php.net/manual/en/session.examples.php
For example to put:
$_SESSION['name'] = $value;
And to get:
$value = $_SESSION['name'];
Below you can find , how to use session in Laravel.
Setting a single variable in session :-
syntax :- Session::put('key', 'value');
example :- Session::put('email', $data['email']); //array index
Session::put('email', $email); // a single variable
Session::put('email', 'test#test.com'); // a string
Retrieving value from session :-
syntax :- Session::get('key');
example :- Session::get('email');
Checking a variable exist in session :-
// Checking email key exist in session.
if (Session::has('email')) {
echo Session::get('email');
}
Deleting a variable from session :-
syntax :- Session::forget('key');
example :- Session::forget('email');
Removing all variables from session :-
Session::flush();
Source : http://tutsnare.com/how-to-use-session-in-laravel/
Thank to all...
Finally i got answer for using session in Getherbert[laravel],
here it is,
use Herbert\Framework\Session;
class Admin extends MyCore{
function index(){
session()->set('age',24);
dd(session()->get('age'));
}
}
OUTPUT :
24
I have just started learning Code Igniter .
I want to know how can I pass a variable from one controller(first_cont.php) to other controller (second_cont.php) ?
Any help would be appreciated .
Thanks in Advance :)
It will depend on the circumstances. If you want to retain the data for some time, then session data would be the way to go. However, if you only need to use it once, flash data might be more appropriate.
First step would be to initialise the session library:
$this->load->library('session');
Then store the information in flash data:
$this->session->set_flashdata('item', $myVar);
Finally, in the second controller, fetch the data:
$myVar = $this->session->flashdata('item');
Obviously this would mean you'd have to either initialise the session library again from the second controller, or create your own base controller that loads the session library and have both of your controllers inherit from that one.
I think in codeigniter you can't pass variable, between two different controller. One obvious mechanism is to use session data.
Ok, here is something about MVC most will readily quote:
A Controller is for taking input, a model is for your logic, and, a view is for displaying.
Now, strictly speaking you shouldn't want to send data from a controller to another. I can't think of any cases where that is required.
But, if it is absolutely needed, then you could simply use redirect to just redirect to the other controller.
Something like:
// some first_cont.php code here
redirect('/second_cont/valuereciever/value1')
// some second_cont.php code here
public function valureciever($value){
echo $value; // will output value1
}
In Codeigniter there are many way to pass the value from one controller to other.
You can use codeigniter Session to pass the data from one controller to another controller.
For that you have to first include the library for session
$this->load->library('session');
Then You can set the flash data value using variable name.
// Set flash data
$this->session->set_flashdata('variable_name', 'Value');
Them you can get the value where you want by using the codeigniter session flashdata
// Get flash data
$this->session->flashdata('variable_name');
Second Option codeigniter allow you to redirect the url from controll with controller name, method name and value and then you can get the value in another controller.
// Passing the value
redirect('/another_controller_name/method_name/variable');
Then you can get the value in another controller
public function method_name($variable)
{
echo $variable;
}
That all....
If you are using session in the first controller then dont unset that session in first controller, instead store the value which you want in the other controller like,
$sess_array = array('value_name1' => 'value1', 'value_name2' => 'value2');
$this->session->set_userdata('session_name', $sess_array);
then reload this session in the other controller as
$session_data= $this->session->userdata('session_name');
$any_var_name = $session_data['value1'];
$any_var_name = $session_data['value2'];
this is how you can pass values from one controller to another....
Stick to sessions where you can. But there's an alternative (for Codeigniter3) that I do not highly recommend. You can also pass the data through the url. You use the url helper and the url segment method in the receiving controller.
sending controller method
redirect("controller2/method/datastring", 'refresh');
receiving controller method
$this->load->helper('url');
$data = $this->uri->segment(3);
This should work for the default url structure. For a url: website.com/controller/method/data
To get controller $this->uri->segment(1)
To get method $this->uri->segment(2)
The limitation of this technique is you can only send strings that are allowed in the url so you cannot use special characters (eg. %#$)