Session message is not working i tried this code and many fix available online
Here id my store function `
public function store(Request $request)
{
// dd($request->all());
$this->validate($request, [
'name' =>'required',
'username' =>'required',
'email' =>'required',
'address' =>'required',
'likes' =>'required',
'gender' =>'required'
]);
$input = $request->all();
Contacts::create($input);
Session::put('flash_message', 'Task successfully added!');
return redirect()->back();
}
And Retrieving by this code
#if(Session::has('flash_message'))
<div class="alert alert-success">
{{ Session::get('flash_message') }}
</div>
#endif
I resolved issue with laravel 6.x
As soon as I moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php everything started working as expected.
I Resolved the Issue with laravel 5.2.
I was having route like this
Route::group(['middleware' => [ 'web','auth']], function () {
.......
}
So Removed the web middle ware
Route::group(['middleware' => ['auth']], function () {
.......
}
and its start working
Analysis: By default Laravel Add web Middleware.
check by php artisan route:list it shows web, web,auth .
so by defining it again redirect two time for the web middleware.
I RESOLVED the issue with laravel 5.2.
I was having all the routes inside this:
Route::group(['middleware' => 'web'], function() {
I remove it because when I used the command php artisan route:list in the Name Middleware column the "web" shows to times: web, web.
If you have AUTH replace by:
Route::group(['middleware' => 'auth'], function() {
Also I delete a duplicate route (in routes.php). Now I just have:
Route::resource('/publicaciones', 'PublicacionesController');
My controller:
return redirect()->back()->with('success', 'Saved!');
My view:
#if(Session::has('success'))
<div class="alert alert-success">
{{ Session::get('success') }}
</div>
#endif
have you include the following namespace
use Session;
instead of the following code
Session::put('flash_message', 'Task successfully added!');
use
Session::flash('flash_message', 'Task successfully added!');
in instead to
return redirect()->back();
try using
return redirect()->route('your route');
When the validation fails, no further code is executed and the previous page is loaded again. This is the reason why session message is not working. In order to check for any validation errors use the following code snippet at the top of your blade file.
#if ($errors->any())
#foreach ($errors->all() as $error)
<div class="alert alert-danger alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $error }}</strong>
</div>
#endforeach
#endif
A bit late for this forum. I encounter this problem, I've been different sites searching for the right solution but none works. Here's my case, I'm using v6.0, and I put the route inside routes\api.php.
I think there is difference of putting the route to the right place or file, can't explain more.
Here's how I solved, I transfer the route from routes\api.php to routes\web.php and thats it after so many researching I now successfully display the flash message.
Try this code
Session::flash('flash_message', 'Task successfully added!');
Session::save();
return redirect()->back();
This worked for me
This will work in case "Session" fails to display errors in your blade view.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Related
I'm trying to flash error messages from my controller back to my view. I tried this with:
\Route::group(['middleware' => 'web'], function ()
flash('Error message');
return Redirect::back();
});
And tried showing it my view with:
#include('flash::message')
However this just seems not to show the message.
I've been looking over the web for some good 2 to 3 hours now and I am at a loss right now.
If this is a duplication of another question somewhere on stackoverflow, then sorry!
To use session flash in Laravel:
web.php
Route::get('/',
function () {
Session::flash('error', 'test');
return view('welcome');
});
In your .blade view file you can access the message using
#if (session('error'))
<div class="alert alert-warning">{{ session('error') }}</div>
#endif
You could replace 'error' with any type of message ('success', 'warning', 'yourOwnMessageIdentifier etc) you'd want to flash.
In controller
use Session;
\Session::flash('msg', 'Error' );
in blade
{!!Session::get('msg')!!}
use simply
\Session::flash('msg', 'Changes Saved.' );
#if(Session::has('msg'))
<div class="alert alert-info">
<a class="close" data-dismiss="alert">×</a>
<strong>Heads Up!</strong> {!!Session::get('msg')!!}
</div>
#endif
Here is my login.blade.php
#if(Session::get('errors')||count( $errors ) > 0)
#foreach ($errors->all() as $error)
<h1>{{ $error }}</h1>
#endforeach
#endif
Here is my LoginController.php:
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => 'ERRORS',
]);
}
And here is my web.php (routes)
// I am customizing the login to do extra checks,
// but I still need the basic auth scaffolding.
Auth::routes();
...
Route::group(['middleware' => 'web'], function () {
Route::view('/login', 'auth.login');
Route::post('/login', 'Auth\LoginController#login')->name('login');
});
When I try to login with a bad user it shows no errors in the view, what am I doing wrong?
Update:
I've tried to change the login.blade.php, as #Seva Kalashnikov suggested, with no luck.
I've also tried #Akshay Kulkarni suggestion with no luck.
Try to remove Session::get('errors') from your if statement in login.blade.php
#if(count( $errors ) > 0)
#foreach ($errors->all() as $error)
<h1>{{ $error }}</h1>
#endforeach
#endif
ShareErrorsFromSession middleware, which is provided by the web middleware group is responsible for $error view variable so it will always be defined (link here)
[UPDATE]
And as #Ohgodwhy pointed, you need to use #if ($errors->any()) Example
So in your case it will be:
#if($errors->any())
#foreach ($errors->all() as $error)
<h1>{{ $error }}</h1>
#endforeach
#endif
Ok, after a few hours I finally found it! I created a Laravel project from scratch and made a diff to find the culprit:
In app/Http/Kernel.php, make sure to get rid of the StartSession middleware:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Session\Middleware\StartSession::class, // <-- Remove this
];
Explanation: I had it there because I read that I had to put it as a middleware (if I wasn't using the Route::group(['middleware' =>'web'] wrapper in my web.php), I think that I forgot it there. I think that putting it there and using the wrapper in web.php somehow truncate the error session before it gets to the view.
Put,
Auth::routes();
Inside middleware group.
Web middleware starts the session.
If you are writing any route outside that middleware group then you can not access the session.
If you use Entrust (or maybe some other packages) and add its classes to $routeMiddleware, the problem can be deriving from that your subsequently added custom classes override the default Laravel classes.
The solution is to move your custom classes to the top of $routeMiddleware array.
I faced same problem. After a lot of digging here and there, I solved it by removing \Illuminate\Session\Middleware\StartSession::class from $middlewareGroups of 'web' in app\http\kernel.php.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, // <-- Remove this
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
It is realted to #halfer's solution.
I got this error Undefined variable: error in Lumen 5.4
web.php
$app->get('/', 'SubscribersController#index');
$app->post('/', 'SubscribersController#store');
controller
public function store(Request $request)
{
$this->validate($request, [
'email' => 'required|email|unique:subscribers,email'
]);
app('db')->table('subscribers')->insert([
'email' => $request->input('email'),
]);
return redirect('/');
}
index.blade.php
{{dd($errors)}}
So, how i can get my error? I can get error only in json format, but i want put this error on index.blade.php how this is possible?
{
"email": [
"The email must be a valid email address."
]
}
I want see this error in index.blade.php
#if($errors->has())
#foreach ($errors->all() as $error)
<div>{{ $error }}</div>
#endforeach
#endif
The lumen documentation states that Lumen does not have the $error variable for views and that you should catch the error $this->validate throws. This way you can add the variables to your view manualy.
Hi friend's i need help how to display success message without using session
Just adding this code before your redirect code:
$request->session()->flash('alert-success', 'User was successful added!');
Laravel 5.1 about Flash Data : http://laravel.com/docs/5.1/session#flash-data
and for your view:
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div> <!-- end .flash-message -->
You can use Bootstrap Alerts view: http://www.w3schools.com/bootstrap/bootstrap_alerts.asp
Append a variable name in URL like:
xyz.com/backend/packages?status=true
At your view get the url components and check if that variable exist:
if(isset($status))
{
echo '<script>alert("You message")<script>';
}
If you want to display any messages between requests without using session, you'll need to store these messages somewhere before a redirect. For example, you could use DB:
Message::create([
'message' => 'Thanks for adding the comment',
'user_id' => auth()->user()->id
]);
And get it after redirect and then delete it:
$messages = Message::where('user_id', auth()->user()->id)->get();
Message::destroy($messages->pluck('id'));
Alternatively you could use files, Redis etc as Laravel itself does when working with sessions.
I am new in laravel and I want to update an existing row in database,but when I click on send button in view (for example 127.0.0.1/laravel/public/Article/update/3 ) I encounter the following error:
MethodNotAllowedHttpException in RouteCollection.php line 201:
Here is my code
Route
Route::get('Article/edit/{id}','ArticleController#edit');
Route::get('Article/update/{id}','ArticleController#update');
ArticleController
public function edit($id)
{
$change = Article::find($id);
return view('edit',compact('change'));
}
public function Update($id, Request $request)
{
Article::update($request->all());
return redirect('Article');
}
Model
public $table = 'Article';
protected $fillable = ['title' , 'body'];
edit.blade.php
<h1>ویرایش بست {{$change->title}}</h1>
{!! Form::model($change ,['method'=>'patch' , 'url'=>['Article/update' , $change->id ]]) !!}
{!! Form::label('title','عنوان') !!}
{!! Form::text('title') !!}
<br>
{!! Form::label('body','متن') !!}
{!! Form::textarea('body') !!}
<br>
{!! Form::submit('send') !!}
{!! Form::close() !!}
#if($errors->any())
<ul class ='alert alert-danger'>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
The easiest way to resolve routing issues with Laravel is to use 'artisan'.
http://laravel.com/docs/5.1/artisan
If you use this command:
php artisan route:list
You'll see every possible route and HTTP verb available for use. Your error is in the RouteCollection so you can always fix these issues by looking at your app/http/routes.php file.
You defined a route as follows:
Route::get('Article/update/{id}','ArticleController#update');
Then you call that route via your form as follows:
{!! Form::model($change ,['method'=>'patch' , 'url'=>['Article/update' , $change->id ]]) !!}
Your routes.php GET definition does not match your form's PATCH method, so you're getting a method not allowed exception because the PATCH route is not defined.
You need this line of code in your routes.php file:
Route::patch('article/update/{id}','ArticleController#update');
I would highly recommend using this instead of defining each method individually:
Route::resource('article', 'ArticleController');
Then run the following command again with artisan to see all routes created:
php artisan route:list