Laravel 5.1 Session not working - php

i have Session in my Controller store
public function store(Request $request)
{
\Session::push('store_pos.items',$request->all());
print_r(\Session::get('store_pos.items')); // This is show array
exit;
}
public function create()
{
$items = \Session::get('store_pos.items');
print_r($items); // in this syntax not show array
}
why session in function create not show ?
I've been using the session put but still does not appear
Thanks

You can do this if you want to return the input if anything error when you submit the form:
$trans = new Transaction();
// Do all the input stuff
if($trans->save()){
// your code if the transaction successfully save
}
return back()->withInput(); // this will return back to the page with input
//or if you prefer facade
return Redirect::back()->withInput();

Is your controller under "web" middleware?
Any routes not placed within the web middleware group will not have access to sessions and CSRF protection, so make sure any routes that need these features are placed within the group.

Related

Laravel allow route to be accessible only from another route

I have /signup/select-plan which lets the user select a plan, and /signup/tos which displays the terms of services. I want /signup/tos to be only accessible from /signup/select-plan. So if I try to go directly to /signup/tos without selecting a plan, I want it to not allow it. How do I go about this?
In the constructor, or the route (if you are not using contructors), you can check for the previous URL using the global helper url().
public function tos() {
if ( !request()->is('signup/tos') && url()->previous() != url('signup/select-plan') ) {
return redirect()->to('/'); //Send them somewhere else
}
}
In the controller of /signup/tos which returns the tos view just add the following code:
$referer = Request::referer();
// or
// $referer = Request::server('HTTP_REFERER');
if (strpos($referer,'signup/select-plan') !== false) {
//SHOW THE PAGE
}
else
{
dd("YOU ARE NOT ALLOWED")
}
What we are doing here is checking the HTTP referrer and allowing the page access only if user comes from select-plan
You are need of sessions in laravel. You can see the following docs to get more info: Laravel Sessions
First of all you need to configure till how much time you want to have the session variable so you can go to your directory config/sessions.php and you can edit the fields 'lifetime' => 120, also you can set expire_on_close by default it is being set to false.
Now you can have following routes:
Route::get('signup/select-plan', 'SignupController#selectPlan');
Route::post('signup/select-token', 'SignupController#selectToken');
Route::get('signup/tos', 'SignupController#tos');
Route::get('registered', 'SignupController#registered');
Now in your Signupcontroller you can have something like this:
public function selectPlan()
{
// return your views/form...
}
public function selectToken(Request $request)
{
$request->session()->put('select_plan_token', 'value');
return redirect('/signup/tos');
}
Now in signupController tos function you can always check the session value and manipulate the data accordingly
public function tos()
{
$value = $request->session()->get('select_plan_token');
// to your manipulation or show the view.
}
Now if the user is registered and you don't need the session value you can delete by following:
public function registered()
{
$request->session()->forget('select_plan_token');
// Return welcome screen or dashboard..
}
This method will delete the data from session. You can manipulate this. You won't be able to use in tos function as you are refreshing the page and you want data to persist. So its better to have it removed when the final step or the nextstep is carried out. Hope this helps.
Note: This is just the reference please go through the docs for more information and implement accordingly.

How to determine if a session with same variable is already there in laravel

I am using Laravel framework. There is a function in controller that creates session with name store_id
StoreController.php
function initiate($id)
{
//Some queries
session['store_id' => 'some value'];
}
Now if I run this function on one tab then session::get('store_id') is going on. But if I open another tab in the same browser then again run the function that means session('store_id') will be again set. How do I handle this situation that if there is already a session then it should redirect to it's perspective url.
Okay first of all, Bruuuhhhh been there and done that
Alright, lets begin. you want that if there is already a session with store_id going on then you want user to redirect or send back.
In your controller add this
public function initiate()
{
if(session()->has('store_id'))
{
//What ever your logic
}
else
{
redirect()->to('/store')->withErrors(['check' => "You have session activated for here!."]);
}
}
Most probably you would be wondering that user can just go to other url after /store/other-urls Yess he can.
To avoid this. Add a custom middleware
php artisan make:middleware SessionOfStore //You can name it anything.
In that middleware
public function handle($request, Closure $next)
{
if($request->session()->has('store_id'))
{
return $next($request);
}
else
{
return redirect()->back()->withErrors(['privilege_check' => "You are not privileged to go there!."]);
}
return '/home';
}
in your main store page. Add an anchor tag Stop Service
Now in your web.php
Route::group(['middleware' => 'SessionOfStore'], function()
{
//Add your routes here.
Route::get('/stop', 'StoreController#flushSession');
});
Now you have restrict access to urls and has checked the sessions.
Now in
public function flushSession()
{
//empty out the session and
return redirect()->to('/home');
}
The Laravel session helper has the function has to check this.
if (session()->has('store_id'))
{
// Redirect to the store
}
else
{
// Set the store id
}
The documentation contains all of the possible functions that can be used with the session helper.

How to redirect different page from same controller function in laravel 5.2

I want to redirect 2 different page from this controller function along with value.Here is my code. It works but both of time url become same.what shuld I do?
//in routes.php
Route::post('/','mycontroller#check');
// in controller.php
public function check(Request $request)
{
$c_email = $request->email;
$c_pass=$request->pass;
$c_type=$request->select;
$var=DB::select("SELECT * FROM reg where email = '$c_email' and Password = '$c_pass' and type = '$c_type'");
if ($var) {
return view('farmer')->with('user',$var);
// return redirect('farmer')->with('user',$var);
}
else {
$msg="Invalid login";
return view('index')->with('show',$msg);
}
}
If you want to actually redirect u can use the redirect() helper as statet in the official docs https://laravel.com/docs/5.3/redirects
You can also pass data
redirect('/my-route')->with(['user' => $var]);
The passed data can then be accesses through the session helper
$var = session('user')
HOWEVER, it seems like you have major issues in your code. Your password does not seem to be encrypted. Also there's no reason to use plain sql instead of eloquent here.
The route that is shown in the browser is defined in your
Route::post('/','mycontroller#check');
If you just return different views, the route does not change. You need to redirect to other views.
If you redirect to other routes you will ofcourse need to add / define them.
Route::get('/my-route', function() {}); // or post etc.

Redirect and pass data from controller

I want to redirect from a controller and pass data;
public function fortest(Request $request)
{
$user = DB::table('user2s')->where('name', $request->name)->first();
if (isset($user))
{
return redirect('/fortest2', ['user'=>$user]);//compact('user'));
//return $this->fortest2($request);
}
}
public function fortest2(Request $request)
{
return $request->name;
}
Route::get('/fortest', 'UserController#fortest');
Route::get('/fortest2/', 'UserController#fortest2');
The code works when calling the controller directly from within the controller. The data type has a model. How can I accomplish this?
If you want to pass data in a redirect, you can use the with() method.
You have to append it to the redirect like so:
redirect('/fortest2')->with('data', 'value');
It will be saved in your current session, so it will be only persistent until you refresh the page again. If you want to store it for longer you have to go with a database/textfile etc. You can then check for it using
if (session()->has('data')) { // check if it exists
$value = session('data'); // to retrieve value
}
You can also send errors with the redirect (from validation i.e.) using withErrors(), sending the current input with it using withInput()
For what you want to achieve, try using this in your controller. This will just send the users name with the redirect:
$user = DB::table('user2s')->where('name', $request->name)->first();
redirect('/fortest2')->with('username', $user->name);
You can then access is via session('username')
You need to use sessions to pass data when using redirect:
return redirect('/fortest2')->with('data', 'some data');
Then get data from session:
$data = session('data');
Or you can persist data in DB and then get it from there.
Try to do like this
public function fortest(Request $request)
{
$user = DB::table('user2s')->where('name', $request->name)->first();
if(isset($user))
{
return redirect('/fortest2/$user->name');
}
}
public function fortest2($name)
{
return $name;
}
Your route
Route::get('/fortest', 'UserController#fortest');
Route::get('/fortest2/{$name}', 'UserController#fortest2');

Laravel 5.2.32: Session flash doesn't work with redirect

I have a controller which has a redirect function:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data);
}
This previousroute is handled by otherControllerMethod() like so:
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Unfortunately, Laravel forgets this session data. I've done this many times before and I have never seen if forget the session flash data after a single redirect. What is going on here? I have tried both adding and removing "web" middleware but nothing works. If anyone knows why this happens let me know.
use Session;
public function myControllerMethod()
{
$data = $this->blabla();
Session::set('data', $data);
return Redirect::to('previousroute')->with('data', $data);
}
public function otherControllerMethod()
{
$data = Session::get('data');
return $this->makeView($data);
}
Try like this. Use the session and set the data in session and get it from where you want.
I have had the same Issue before. Basically I needed to call send function when redirecting using Redirect facade. So you need to change your myControllerMethod to:
public function myControllerMethod()
{
$data = $this->blabla();
return Redirect::to('previousroute')->with('data', $data)->send();
}
As send() function of class Symfony\Component\HttpFoundation\Response calls the function sendContent() which sends the data when redirecting.
Hope this helps.
In myControllerMethod you are passing the data obj/var as a Request.
In otherControllerMethod you are requesting the Session data which is not set.
In order to put data to the session you should do:
Session::put('data','value')
and then it will be available with:
Session::get('data');

Categories