Laravel return back with flash data - php

I have a contact form. On submit the POST request goes to a controller that handles the contact form (checks the request and emails the data). At the bottom of the controller I have this:
return back()->with('flash-message', 'Message!');
In the view I try to echo the message with
{{ session('flash-message') }}
This doesn't seem to work. The message is not in the session.
What could be wrong?
Im using:
Laravel version 5.2.7

please take Session variables with this way..
return redirect()->back()->with('flash-message','message');
and in View..
{{Session::get('flash-message')}}

I figured it out. It has to do with the Laravel 5.2 update. The middleware which is responsible for making that flash data available to all your views is not being utilized in normal Routes anymore. It was moved from the global middleware to the web middleware group. This post explains the issue and how to fix it.
Laravel 5.2 $errors not appearing in Blade
This post explains 2 ways to fix it:
In your kernel.php file, you can move the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::class back to the protected $middleware property.
You can wrap all your web routes in the web middleware group (see below). Also place the Routes that handle the form here:
Route::group(['middleware' => 'web'], function() {
// Place all your web routes here...
});

You can do this.In the controller:
Session::flash('message','Empty input not accepted');
return back();
And in the view file to use this Session you can do same as above mentioned:
{{ \Session::get($message) }}
Hope this helps you....

Related

Laravel 8 Auth middleware protected route failing

I am building my first Laravel app with the Metronic 8 Laravel theme. It uses Breeze for authentication. I changed a couple of things around - created a welcome page for non-logged-in users, and moved the main template that was the index to an auth protected "/dashboard". The problem is that it still tries to load the dashboard Blade template, regardless of authentication, resulting in an error.
Route
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth'])->name('dashboard');
Here's Authenticate, where it should redirect non-authenticated users to the login page.
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
When I'm not logged in and navigate to the dashboard URL, it attempts to load the dashboard Blade template, which calls a menu function that checks the user permissions for menu items. Unfortunately, since there is no user, the application blows up from passing a null value to a method expecting a user array/object.
Any ideas on where to look for the problem? It seems to me that the auth middleware should redirect to the login page before trying to load the Blade template when not logged in.
I would put the middleware at the beginning of the route like this, though I'm sure it's not causing the problem-
Route::middleware(['auth'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
Aside from that, please provide some information on the error itself like what the error is about/what is says..etc...
First of all, make sure you have a login named route defined in your routes/web.php file. It should look something like:
Route::get('/login', '<controller>#<method>')->name('login');
The important bit is ->name('login') so that the Authenticate middleware can correctly identify the route to redirect to. Change <controller>#<method> appropriately to route to the login method of your app.
Wakil's answer is irrelevant and actually opposite of the documentation. Your syntax is correct.
I figured out the issue. Keen Themes put a call to a method to build an array of menu items in the web routes file. That was making the call to the offending code. After I wrapped that in an auth check the error was fixed, and everything works as expected.

Laravel 5.2 token mismatch and middleware error

I'm using Laravel 5.2 and doing all authentication manually. So, although everything works, but I get a token mismatch error and the reason is that I'm not passing my routes through the web middleware in my routes file:
Route::group(['middleware'=>['web']],function (){
Route::get('/', function () {
return view('welcome');
})->name('home');
});
Route::social();
where Route::social(); is
public function social() {
$this->post('/signup',['uses'=>'UserController#postSignUp','as'=>'signup']);
$this->post('/signin',['uses'=>'UserController#postSignIn','as'=>'signin']);
$this->get('/dashboard',function() {
return view('dashboard');
})->middleware('auth');
}
But if I move Route::social(); to the web middleware group, it doesn't count errors and so return empty errors even if there are. How do I get around with it? I want both things!
I've the token field in my form using {!! Form::token() !!}
You are probably manually adding an $error array to your view, the web middleware will do the same thing so this will be overwritten. The web middleware group includes \Illuminate\View\Middleware\ShareErrorsFromSession which creates an error variable in the views with validation errors.
There are two ways to fix this. One is to only include the \App\Http\Middleware\VerifyCsrfToken middleware for this route. The other, wich I would prefer, is to add the route to the web middleware group, but use another name for your array with errors.

How to Session::flash with default AuthController in Laravel

After hour wasted on such a (as I thought) minor thing, I need Your help.
I've made a quickstart with Laravel using php artisan make:auth command. Then I redefined login method in AuthController. Now it looks like this:
protected function login(Request $request) {
if (Auth::attempt(["name" => $request->username, "password" => $request->password])) {
return Redirect::route("home")->with("message", "Zalogowano");
} else {
return Redirect::route("get.login")->with("message", "Nie zalogowano");
}
}
In my view I've got{{ Session::get("message") or "" }}
and my message doesn't show up.
I've also tried Session::flash("message", "message string"), same effect.
Any ideas what could I do to show a message after (un)successfull login?
PS. Should've mention logging in and out works just fine.
Are your routes defined within the 'web' middleware group (including the Auth routes)? The 'web' middleware group handles starting the session. More specifically the middleware \Illuminate\Session\Middleware\StartSession::class handles starting the session. No session, no messages. Your routes should be wrapped in the Route group like so:
Route::group(['middleware' => 'web'], function () {
// Define routes here
});
Take a look in app\Http\Kernel.php to see what Middleware classes are included in this Middleware group and dive into them.
Try {{ $message }} in your template.
When you use ->with("varnamehere", "value") to flash data on the end of your redirect, you can simply access the variable in your template with $varnamehere.
The variable simply exists, ready for use in your template.
There doesn't seem to be a section in the manual that clearly explains this.
In your view template try:
#if (session()->has('message') ? session()->get('message') : "") #endif
It will print the message if is set..
Hope it helps..

Laravel 5.2 Auth with TwigBridge Session store not set

As mentioned in the title I'm using Laravel 5.2 and I've set up TwigBridge so I can use twig for my views. I'm just using the basic Auth package that comes with Laravel. The problem is when I use twig templates I get the following error:
An exception has been thrown during the rendering of a template ("Session store not set on request.") in "...resources/views/auth/register.twig" at line 17.
This is pointing to a use of the {{ old('name') }} call. I've tried switching it to input_old as I think TwigBridge prefers that, but that didn't help. If I use the blade template there's no problem though. I'm not doing anything special either. I just rename the blade template so it isn't called, and my register twig template is called instead since it uses the name register.
The old values are fetch from the session. To get these values to store in session & fetch these values back, you need to apply \Illuminate\Session\Middleware\StartSession and
\Illuminate\View\Middleware\ShareErrorsFromSession middlewares to your routes. Both of these are a part of middleware group web.
You can apply web middleware group to all your routes(unless you are creating an API), like this:
Route::group(['middleware' => ['web']], function () {
Route::get("login" , "AuthController#getLogin");
//Similarly all other routes here
});

Laravel 5.2.* redirect->back->with doesnt work

I want to write some data to my database, if the query fails I want to display an error.
I tried the following:
return redirect()->back()->with('data', ['Database Error!']);
The redirect works great, but I cant read out the response in $data
My Blade:
#if (session()->has('data'))
<div class="alert alert-danger" role="alert">...</div>
#endif
//Second try
<?php if(session('data')) echo $message; ?>
But both methods doesn't work, i read a lot of L5.2 Docs but nothing works.
Do i need to modify the session config?!?
Or what is the problem?
try
return back()->with('data', ['Database Error!']);
back() will take you to the previous page with a data variable that holds 'Database Error!'
This is a breaking problem with the 5.2 upgrade. What's happening is the middleware which is responsible for display the Session message in all your views is not being utilized because it was moved from the global middleware to the web middleware group.
There are two ways to fix this:
In your kernel.php file(app/Http/Kernel.php), you can move the middleware \Illuminate\View\Middleware\ShareErrorsFromSession::class back to the protected $middleware property.
Wrap all your web routes with a route group and apply the web middleware to them:
Route::group(['middleware' => 'web'], function() {
// Place all your web routes here...(Cut all `Route` which are define in `Route file`, paste here)
});

Categories