Passing information between pages with Laravel - php

I need to pass information between pages.
I would usually just use sessions in plain PHP. I wonder if there is a more correct way to do this on Laravel.
First_page.php
<?php
session_start();
$_SESSION["ID"] = 'item_id';
?>
Second_page.php
<?php
session_start();
echo $_SESSION['ID'];
#"item_id"
?>
How is this supposed to be done in Laravel?

Just use Session.
Session::flash(); //or Session::put
Session::flash('values', $passvalues);
Redirect::to('/add1');
$oldinput = Session::get('values');

In laravel you can pass a variable in your url i.e. :
In routes.php
Route::get('/page1', 'YourController#Yourfunction');
Route::get('/page2/{id}', 'YourController#loadpage2');
In your controller.php
public function Yourfunction(){
return view('page1');
}
public function loadpage2(id){
return view('page2', compact('id'));
}
in your view have a link to url /page2/3 where 3 is your id

If you want to use session then you need to do 2 things.
save session variables in your controller
display session variables in your view
In your controller you can use something like
session()->put('your_session_variable','some value');
In your view then you can display that session variable
#if(session()->has('your_session_variable'))
{{Session::get('your_session_varible',"session_not_set(default value)") }}
#endif
Its good to use default value for displaying session variables (many times that session variable is not set).

Related

How to Use Session in Getherbert [Laravel]?

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

How to pass a data with redirect in codeigniter

In my controller i used this way. i want to pass a variable data to my index function of the controller through redirect
$in=1;
redirect(base_url()."home/index/".$in);
and my index function is
function index($in)
{
if($in==1)
{
}
}
But I'm getting some errors like undefined variables.
How can i solve this?
Use session to pass data while redirecting. There are a special method in CodeIgniter to do it called "set_flashdata"
$this->session->set_flashdata('in',1);
redirect("home/index");
Now you may get in at index controller like
function index()
{
$in = $this->session->flashdata('in');
if($in==1)
{
}
}
Remember this data will available only for redirect and lost on next page request. If you need stable data then you can use URL with parameter & GET $this->input->get('param1')
So in the controller you can have in one function :
$in=1;
redirect(base_url()."home/index/".$in);
And in the target function you can access the $in value like this :
$in = $this->uri->segment(3);
if(!is_numeric($in))
{
redirect();
}else{
if($in == 1){
}
}
I put segment(3) because on your example $in is after 2 dashes. But if you have for example this link structure : www.mydomain.com/subdomain/home/index/$in you'll have to use segment(4).
Hope that helps.
Use session to pass data while redirecting.There are two steps
Step 1 (Post Function):
$id = $_POST['id'];
$this->session->set_flashdata('data_name', $id);
redirect('login/form', 'refresh');
Step2 (Redirect Function):
$id_value = $this->session->flashdata('data_name');
If you want to complicate things, here's how:
On your routes.php file under application/config/routes.php, insert the code:
$route['home/index/(:any)'] = 'My_Controller/index/$1';
Then on your controller [My_Controller], do:
function index($in){
if($in==1)
{
...
}
}
Finally, pass any value with redirect:
$in=1;
redirect(base_url()."home/index/".$in);
Keep up the good work!
I appreciate that this is Codeigniter 3 question, but now in 2021 we have Codeigniter 4 and so I hope this will help anyone wondering the same.
CI4 has a new redirect function (which works differently to CI3 and so is not a like for like re-use) but actually comes with the withInput() function which does exactly what is needed.
So to redirect to any URL (non named-routed) you would use:
return redirect()->to($to)->withInput();
In your controller - I emphasise because it cannot be called from libraries or other places.
In the function where you are expecting old data you can helpfully use the new old() function. So if you had a key in your original post of FooBar then you could call old('FooBar'). old() is useful because it also escapes data by default.
If however, like me, you want to see the whole post then old() isn't helpful as the key is required. In that instance (and a bit of a cheat) you can do this instead:
print'<pre>';print_r($_SESSION['_ci_old_input']['post']);print'</pre>';
CI4 uses the same flash data methods behind the scenes that were given in the above answers and so we can just pull out the relevant session data.
To then escape the data simply wrap it in the new esc() function.
More info would be very helpful, as this should be working.
Things you can check:
Is your controller named home.php? Going to redirect(base_url()."home"); shows your home page?
Make your index function public.
public function index($in) {
....
}

how to pass a variable from one controller to the other in Code igniter

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. %#$)

Session doesn't hold custom userdata

I'm new to CodeIgniter and I started to use the session library.
I have autoloaded the session library and trying to save the current user_id to the session userdata array. But the information is gone when I try to read it on an other page..
The native PHP sessions work just fine (tested it), so it must be something from CI.
I programmed a simple test page where I test the following:
Set the session userdata.
Test page shows the userdata correctly.
Uncomment the set session data lines in the code of the controller and reload the page.
Test page doesn't show the userdata.
The code of the controller:
class Welcome extends CI_Controller {
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
}
Code of the view:
<?php
echo $this->session->userdata('test');
?>
Why does the view display the session_id and not the "test" variable you created?
Did you test
<?php
echo $this->session->userdata('test');
?>
in the view file?
CI's sessions are cookies, not PHP native sessions. Calling sessions in a view works (IIRC), but since your view is loaded in the same request the session is created, it won't be set.
You need to call it on another request (i.e. another controller), or set the session somewhere else (in another controller, via AJAX could work also), or use native PHP $_SESSION array instead.
I think your actual code is just a test case, otherwise why not just
public function index(){
$data = null;
$data['test'] = "Yeeeeh!!";
$this->session->set_userdata($data);
$this->load->view('welcome_message', $data);
}
in view:
<?php
echo $test;
?>

Codeigniter: Best practice for View accessing session

From what I've read, the View should be as simple as possible.
Is it good practice to access session variables in the view?
ie.
// in the view
<?php if ($this->session->userdata('is_logged_in') : ?>
// stuff
<?php endif; ?>
The straight answer to your actual question is simply: Yes, it is fine to access session variables inside the view. Because session or regular, they are exactly that, a variable. A place to store information.
I do this quite often with using the $this->session->flashdata for showing messages in a defined area of the view inside the header.
The reason I say this is because the others seem to skip over your actual question to get at 'why' you asked the question, "where is the best place to check for auth?" for which Cadmus's answer is right on the head of how I handle this as well, but again, don't think you shouldn't access session "data" from the view, but checking for authentication needs to happen at the Controller level for sure.
If you don't want to put these kind of "logic" into the view (a good thing IMO), you need to but in the controller. This way, the view itself will get cleaner too:
<?php if($logged_in): ?>
do stuff
<?php else: ?>
do different
<?php endif; ?>
with $logged_in coming from the view that does all the session work. You could either write your own controller, that extends from the CI controller so that the classes extend you controller or abstract it to a seperate Session class that has some static methods. I think that extending the CI controller with your own logic seems to be the cleanest way if you do lots of session handling.
if you use this variables so much you can use a helper. And you can acces to it like:
<?php if (is_logged_in()) : ?>
<!--your html code -->
<?php else ?>
<!--more html code -->
<?php endif;?>
then in your helper, that is called access_helper, for example, you have:
<?php
function is_logged_in() {
return $this->session->user_data('is_logged_in');
}
?>
I am Not Sure about the best practice but I like to give my way of handling the session and views.
I put the session data to check the user is logged in or not to the constructor of my controller.
then I automatically get the session validation that the page which I load from that controller is getting automatic get session cover.
public function __construct() {
parent::__construct();
if (!$this->session->userdata('user_data')) {
return redirect('login');
} else {
redirect('dashboard');
}
$this->load->model('customer_model');
}
and the for success or failed message to the view I use flash data.
private function _falshAndRedirect($successful, $successMessage, $failureMessage) {
if ($successful) {
$this->session->set_flashdata('feedback', $successMessage);
$this->session->set_flashdata('feedback_class', 'alert-success');
} else {
$this->session->set_flashdata('feedback', $failureMessage);
$this->session->set_flashdata('feedback_class', 'alert-danger');
}
return redirect('customer/view_customer');
}
here I use the private function to get my message to the view.
then you create the functions and that functions get automatic the "cover of the session".
Hope this will help.
It is impossible to access a session variable from a helper. The simplest is to access the session variable from a view.
<?php if ($this->session->user_data('is_loggen_in'): ?>
<!-- HTML stuff -->
<?php endif; ?>
In my opinion, I do not think that affects the philosophy of MVC pattern because the session is global information.

Categories