Laravel flash or session messages not expiring [ not maintained Updated ] - php

Updated after some research
After some research I conclude that, my sessions are not maintained until I save them explicitly, below code works well, but WHY???? Ref here
Session::put('lets_test', 2);
Session::save();
Old Question
I'm new to laravel 5.3, and stuck at a problem. My Laravel Session or Flash messages are not expiring they display each time page is reloaded, until I use Session::flush() Below is my controller code
<?php
namespace App\Http\Controllers;
use Session;
use Auth;
use Illuminate\Http\Request;
use App\User;
use App\Hospital;
use App\Wpr;
use Helper;
class OperatorController extends Controller
{
public $user_detail;
public function __construct()
{
$this->middleware('auth');
$this->middleware('operator');
}
public function store (Request $request){ //Form is being submitted here
//My logic here
Session::flash('user_message', 'Thank You');
return redirect('/operator/wpr');
}
}
I've also used Session::set('user_message', 4);
and blade view
#if(Session::has('user_message'))
<div class="message animated tada">
{{ Session::get('user_message') }}
</div>
#endif
I've tried with Session::forget('user_message') but no luck.
Updating my post after some research. I've got somewhat close to my problem by reading this post on stack because this question is exactly same to my problem but unfortunately it still persists, I've changed my session storage from file to database (in case file permissions to storage directory). What might be other possibilities?
Please help, thanks in advance.

Ultimately, somehow, I managed to find solution for my problem, of not sustaining sessions. I don't think its any issue related to file permission. Now I'm saving my session explicitly and removing it explicitly.
Made a Helper class added two methods
public static function SetMessage($message, $type){
Session::put('user_message', $message);
Session::put('user_message_type', $type);
Session::save();
}
public static function ForgetMessage(){
Session::forget('user_message');
Session::forget('user_message_type');
Session::save();
}
and within Controller class
Helper::SetMessage('Record updated successfully', 'success');
and within blade view tempalte
#if(Session::has('user_message'))
<div class="alert alert-{{ Session::get('user_message_type') }}">
{{ Session::get('user_message') }}
{{ Helper::ForgetMessage('user_message') }}
</div>
#endif
I hope this might help someone who is facing such kind problem. But why is it so, still unknown, maybe one day I'll post the reason too. More suggestions are welcomed, if this could be done in a better way.

try this:
if(isset($_SESSION['user_message'])) {
$message = $_SESSION['user_message'];
unset($_SESSION['user_message']);
return $message;
}

In your (Laravel) blade add $request->session()->forget('key'); or Session::forget('key'); at the end of if loop this will end or delete the session of that key. This may help you for more reference about session of laravel 5.3 visit laravel 5.3

Related

Laravel 5.2 : Do something after user has logged in?

(I'm a beginner of Laravel)
I'm using Laravel 5.2. I have successfully enabled the Authentication; by doing the php artisan make:auth and stuffs.
So my login is working.
Now i need to do something once someone has logged in. For an simple example:
LOGIN:
Once a user has logged in, write a value into Session.
For example: $request->session()->put('UserAgent', $ClientUserAgent);
LOGOUT:
Same thing to do, once a user has logged out, delete the custom Session value.
For example: $request->session()->forget('UserAgent');
I'm not sure whether there are (things like) hooks or Event Listeners, Event Handlers, or something like that.
How can i do it please?
For newer versions of Laravel
If you are only doing something very simple then creating an event handler seems overkill to me. Laravel has an empty method included in the AuthenticatesUsers class for this purpose.
Just place the following method inside app\Http\Controllers\LoginController (overriding it):
protected function authenticated(Request $request, $user)
{
// stuff to do after user logs in
}
For the post login, you can do that by modifying App/Http/Controllers/Auth/AuthController.php
Add authenticated() into that class to override the default one:
use Illuminate\Http\Request;
protected function authenticated(Request $request, User $user) {
// put your thing in here
return redirect()->intended($this->redirectPath());
}
For the logout, add this function into the same class:
use Auth;
protected function getLogout()
{
Auth::logout();
// do something here
return redirect('/');
}
You could try setting up event listeners for the Auth events that are fired.
You can setup a listener that listens for Illuminate\Auth\Events\Login to handle what you need post login and Illuminate\Auth\Events\Logout for post logout.
Laravel Docs - Authentication - Events
Alief's Answer below works fine as expected. But as i googled through, using the Event Handlers is probably the more preferred way. (It works like custom hooks).
So without any less respects to Alief's Answer below, let me choose --> this Event Handers approach i just found out.
Thanks all with regards!
If you are testing, with authenticated(Request $request, User $user) method dont use alert inside this method to test, it will not show any result, so better put some insert query or something like that to test this method.
Why not simple check for
if(Auth::check()){
//your code
}
Make sure you include use Auth;

How to access cookie from view in PHP Laravel 5

I can access cookie in controller then pass it to view
//HomeController.php
public function index(Request $request)
{
$name = Cookie::get('name');
return view('index', ['name'=> $name]);
}
But I want to write a small control (widget) that can fetch data from cookie without concern of parent controller. For example, header, footer widgets could fetch its own data without main page controller knowing which data is needed.
I can query the data from database by using View Composer. But, how can I access data from view in the request cookie ?
Using static function with defining namespace and etc is a not safe.
Cuz maybe in next versions of framework this namespace can change.
It's better to use helper functions.
{{ request()->cookie('laravel_session') }}
or
{{ cookie('laravel_session') }}
Tested on working app with Laravel 5.2
You can use {{ Cookie::get('laravel_session') }} to print out the cookie inside your view.
You can use
{{\Illuminate\Support\Facades\Cookie::get('laravel_session')}}
in a blade template
You can use:
$response = new \Illuminate\Http\Response(view('your_view'));
$response->withCookie(cookie('cookieName' , 'cookieValue' , expire));
return $response;
or
\Cookie::queue('cookieName', 'cookieValue', expire);
return view('your_view');
I've used both of them.

Get current route name in AppServiceProvider in Laravel 5.1

I have an installation of Laravel 5.1 and I want to share the route name with all my views. I need this for my navigation so I can highlight the corresponding navigation menu button depending on which page the user is on.
I have this code in my app\Providers\AppServiceProvider:
public function boot()
{
$path = Route::getCurrentRoute()->getName();
view()->share('current_route_name', $path);
}
and I am using this namespace:
use Illuminate\Support\Facades\Route;
but I am getting this error in my view:
Call to a member function getName() on a non-object
the interesting part is that if I write this in view it works with no problems at all:
{{ Route::getCurrentRoute()->getName() }}
Could anyone help me? am I not using the correct namespace or maybe it is not even possible to use Route at this point in the application?
Thank you!
you can use view share under view composer.
view()->composer('*', function($view)
{
$view->with('current_route_name',Route::getCurrentRoute()->getName());
});
Or
view()->composer('*', function($view)
{
view()->share('current_route_name',Route::getCurrentRoute()->getName());
})

Laravel Passing variable not working

Hello People here is my code i have used in controller...
public function bulk()
{
return View::make('bulk')->with('message','hii there');
}
my route file contains...
Route::get('bulk',array('uses'=>'HomeController#bulk'))->before('auth');
In my view Iam testing it by ...
#if(Session::has('message'))
Present
#else
not Present
#endif
The page is making a view with the message 'not Present' why is it??
I even tried
return Redirect::to('bulk')->with('message','hii there');
I get an erro mesage on Console
mypro/public/bulk net::ERR_TOO_MANY_REDIRECTS
What could be the problem?? is there any issues with name?? I tried this method earlier which worked fine for me.... :(
Iam using Blade Template..
You are confusing Redirect and View. You use Session::get to access variables passed to redirects. For views (as in your case), with will pass an simple PHP variable into your view. So your check should be:
#if(isset($message))
{{{ $message }}}
#else
No message!
#endif
Read more here
As per the docs, you need to access the "with" value in the view using a PHP variable, it's not passed via the session. In your case, that would be $message. If you want to use the session, you should use Session::flash() or Session::put().

Can't establish proper routes in Laravel 4

So sorry to bother y'all, but I was wondering if anyone could help me. I'm having a wee bit of a problem with my code in Laravel, being used to working from scratch rather than with frameworks. I made use of the Laravel Bootstrap Starter Site and I'm trying to add additional pages, but the routing isn't exactly co-operating. It's rather frustrating.
The Controller: app/controller/community/CommunityController.php
<?php
class CommunityController extends BaseController {
public function index() {
return View::make('community.index');
}
}
?>
The View
#extends('site.layouts.default')
{{-- Content --}}
#section('content')
#foreach ($posts as $post)
<div>
I'm just going to put this here...
</div>
#endforeach
{{ $posts->links() }}
#stop
And finally, last but not least, my routes.
Route::get('community', array(
'uses' => 'CommunityController#index',
'as' => 'community.index'
));
Now, I have this nagging feeling that I'm missing something rather small, but for the life of me I can't figure it out. If anyone would be so kind to explain what I'm doing wrong, I'd appreciate it. Especially since I can prevent this kind of problem happening in the future as well.
With friendly regards,
User who still hasn't picked out a good name
Edit: Sorry I forgot to mention this. I removed public, so I don't know if that influences anything. If it does, again, sorry for forgetting to mention this in the beginning.
you can try to bind the whole route to the controller, using
Route::controller('community', 'CommunityController');
then in your controller you have to prefix the controller methods with HTTP verbs.
Your index() method will be
public function getIndex() {
return View::make('community.index');
}
Just fire composer dump-autoload in root of your project folder from terminal / console.
It'll load your controller which is in subfolder.

Categories