I have a page 'A'. I create a session variable on this page.
This page is then redirected to a function 'A' in a controller 'A' using window.location.
I try to access the session variable in the function 'A' using the following line
var_dump($request->session->get('variableSetOnPageA'));
This returns NULL.
Why? I need the 'variableSetOnPageA'.
You can also get Session variable in Laravel like below in any of your function in Controller file:
$value = Session::get('variableSetOnPageA');
And you can set your Session variable like below in any of your function:
$variableSetOnPageA = "Can be anything";
Session::put('variableSetOnPageA',$variableSetOnPageA);
In your Controller file, make sure you add below code at top:
use Session;
You ought to invoke the session method from \Illuminate\Http\Request:
$request->session()->get('foo')
or global helper function
session('foo')
Important: It is very important that you call save function after you set any session value like this:
$request->session()->put('any-key', 'value');
$request->session()->save(); // This will actually store the value in session and it will be available then all over.
Check if you have $request available in the function.
public function A(Request $request) // Notice Request $request here.
{
$value = $request->session()->get('your-key');
//
}
This might be help you
if (session()->has('variableSetOnPageA')) {
$result=session()->get('variableSetOnPageA')
}
Related
I'm using a custom PHP framework which is largely based on CodeIgniter.
In one of my controller files, I've set a class property called $orderId. After the user has filled in the form and submitted, I'll do a DB insert, get the order no. and override the $orderId class property value with that order no.
Then I'll redirect to the submit page where I want to access that updated $orderId class property value. This final part is not working, the submit class gets a blank value for property $orderId.
Where am I going wrong pls? The basic example below. Maybe I can't do this because of the redirect and should use a session var instead?
Thanks!
[EDIT] Or I could pass the orderId as the 3rd URL param in the redirect. E.G. redirect('orders/submit/'.self::$orderId); in which case I'll turn all the self:: instances into $this-> for class level scope.
class Orders extends Controller {
private static $orderId;
public function __construct() {
// assign db model
}
public function index() {
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = [
// form data to pass to db model
];
self::$orderId = 12345; // example order no. return from db model
if(!empty(self::$orderId)) {
redirect('orders/submit');
}
}
}
public function submit() {
$data = [
'orderId' => self::$orderId
];
$this->view('orders/submit', $data);
}
}
The issue itself is a fundamental architecture problem. static only works when you're working with the same instance. But since you're redirecting, the framework is getting reinitialised. Losing the value of your static property. Best way to go about doing this is by storing the order id in a session variable and then read that variable. Sessions last for the as long as the browser window is open
I have the following route in my routes.web.php. Looks like this...
Route::get('/spielerAuswahl/{somevar}', 'SpielplanController#getHeimGast');
In the variable {somevar} I have for example Nr1=111&Nr2=222. The route works fine in a get to SpielplanController...
public function getHeimGast(){
$var = $somevar;
return view('test')->with('variableControllerSomevar', $var);
}
In this function I want to put the Nr1=111&Nr2=222 in the $var and make then an easy output of this variable in the view. How to get that?
Though the answer come late, but you can put Nr1=111&Nr2=222 as uri with proper encoding. For javascript, encodeURIComponent can be used to escape certain characters to form a valid URI:
encodeURIComponent('Nr1=111&Nr2=222');
// output: Nr1%3D111%26Nr2%3D222
To request server, using this url:
http://example.com/spielerAuswahl/Nr1%3D111%26Nr2%3D222
The controller function then receives correct form of variable as follows:
public function getHeimGast ($somevar) {
$somevar // = Nr1=111&Nr2=222
}
Only URI segments can be map as route variables in Laravel, no query string variables.
You can simply fetch those like these:
public function getHeimGast(){
$vars = request()->all();
return view('test', $vars);
}
In your test blade, you can use those query vars, eg( Nr1=111&Nr2=222 ) as:
$Nr1, $Nr2 ... and so on...
NOTE: given a query like this: /spielerAuswahl?Nr1=111&Nr2=222
I have mysterious issue with kohana framework.
I create session variable in controller function:
public function action_authorise()
{
session_start();
$_SESSION["user"] = "superAdmin";
}
Later in the same controller's another function I try to access this season:
public function action_getSession()
{
$this->template->test = $_SESSION["user"];
$this->template->content = View::factory('admin/main');
}
The problem is that when I call $test variable in admin/main view it returns empty string, but if I call implicitily $_SESSION["user"] in admin/main view, it returns "superAdmin" as it should.
Can anyone see mistake while calling session variable in controller? Thanks
The problem here is that you're passing the variable test to the view template and it needs to be passed to the view admin/main. You can do this a couple of ways, pick whichever one you like best:
// Create the view object
$partial_view = View::factory('admin/main');
// Assign the session value to the partial view's scope as `test`
$partial_view->test = $_SESSION["user"];
// Assign the partial view to the main template's scope as `content`
$this->template->content = $partial_view;
Shortcut syntax:
$this->template->content = View::factory('admin/main', array(
'test' => $_SESSION['user'],
));
You passing test variable to template view, but trying to access it it admin/main view. There is no test variable in admin/main view. These are different views. Each one has its own variables.
You should set test to admin/main view like:
public function action_getSession()
{
$this->template->content = View::factory('admin/main')
->set('test', $_SESSION["user"]);
}
Also there is very usefull Session class in Kohana. It takes care of session business within framework.
Take a look at user guide.
I have the following route I'm setting.
$app->post(
'/:device/admin/(/)',
'get_user',
$validate_user(
array(
'Admin',
'Manager'
),'
templates'
),'
render_bronzeservice'
)->conditions(
array('device'=>'(tablet|desktop|mobile)')
);
I want to be able to pass the route variable :device to the function $validate_user
How do I do this?
For the function render_bronzeservice, it simply expects a parameter for the device, but this does not work for custom functions or I can't figure it out.
Any help is appreciated!
Ok well I found a workaround for now, its ugly but it will work. Since I get the user data in the function before it, I do the check there for the parameter.
Oddly for some reason it does not send it as a string? But sends it as a route object to the first function.
So my get_user function looks like this.
function get_user($route){
global $user;
global $device;
//If there is any route device info...
if(isset($route->getParams()['device'])){
$device = $route->getParams()['device'];//set the device sent from the route.
}
if (isset($_SESSION['userid']) && !empty($_SESSION['userid'])) {
//Do database lookup on userID and set to global $user
//echo "User Found";
$user = User::find(array('id' => $_SESSION['userid']));//sets the user super global variable from the database accordingly.
}else{
//echo "User Not Found<br/>";
}
}
By using a global variable to keep track of the device, I can then read it in the next function in line $validate_user by declaring global in that function.
It's a weird workaround, but working for now.
I want to get last inserted id, and then assign it to a global variable to use it later.
I'm use callback_after_insert as the following:
$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
$this->lastInsertedId = $primary_key;
}
Then, when use the $this->lastInsertedId to get its value, but I do not find any value stored.
function featured_ad_offer() {
echo $this->lastInsertedId;
#$data['content'] .= $this->load->view('featured_ad_offer', '', true);
$this->load->view('index', $data);
}
There is an error message say Undefined property: Content::$lastInsertedId
Now, how to do that ?
Please try declaring your variable in class (assuming both functions are in the same class) right after "declaring" class itself i.e.
class Blog extends CI_Controller {
private $lastInsertedId = NULL;
public function fcn1() {$this->lastInsertedId = 3.14;}
public function fcn2() {var_dump($this->lastIndertedId);}
}
If you really mean using it as global variable you need to declare it in CI_Controller, or better yet create file in /core/Public_Controller that extends CI_Controller and let all your controllers be extended not by CI_Controller but Public_Controller therefore you can easily declare variables that are "global".
For more information on extending use this tutorial by Phil.
If you have troubles here is a user guide link.
There is another option (not recommended!) config class,
$this->config->set_item('item_name', 'item_value'); //setting a config value
$this->config->item('item name'); //accesing config value
maybe you can use this to get the last inserted id
$this->db->insert_id();
store it in the session
$this->load->library('session');
$this>session->set_userdata('last_inserted_id');
and use this session variable in other places
$last_inserted_id = $this->session->userdata('last_inserted_id');
wish this help :D
The solution that you need it can easily be resolved with Codeigniter sessions. So for example, what you can do is:
$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
$this->session->set_userdata('last_insert_id', $primary_key);
}
Make sure that you have session class loaded first. The best way to do it is to actually have the sessions library at the autoload.
Now to actually call the last_insert_id again, you can simply do it by calling:
echo $this->session->userdata('last_insert_id');
So in your example you can simple do:
function featured_ad_offer() {
echo $this->session->userdata('last_insert_id');
#$data['content'] .= $this->load->view('featured_ad_offer', '', true);
$this->load->view('index', $data);
}