Laravel 4 how to display flash message in view? - session

I'm trying to get my flash message to display.
This is in my routing file
Route::post('users/groups/save', function(){
return Redirect::to('users/groups')->withInput()->with('success', 'Group Created Successfully.');
});
This is in my view
{{ $success = Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif
But nothing is working.
When I try this, I get an error Variable $success is undefined. But it actually shows the flash message too.
{{ Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif

This works for me
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif

if you are using bootstrap-3 try the script below for Alert Style
#if(Session::has('success'))
<div class="alert alert-success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif

when you set variable or message using ->with() it doesn't set the variable/message in the session flash, rather it creates an variable which is available in your view, so in your case just use $success instead of Session::get('success')
And in case you want to set the message in the session flash the use this Session::flash('key', 'value'); but remember with session flash the data is available only for next request.
Otherwise you can use Session::put('key', 'value'); to store in session
for more info read here

two methods:
Method 1 - if you're using
return Redirect::to('users/groups')->withInput()->with('success', 'Group Created Successfully.');
under your controller create(), add in
$success = Session::get('success');
return View::make('viewfile')->with('success', $success);
then on view page,
#if (isset($success))
{{$success }}
#endif
What's happening in method 1 is that you're creating a variable $success that's passed into your create(), but it has no way of display $success. isset will always fail unless you set a variable to get the message and return it.
Method 2 - use return Redirect withFlashMessage
return Redirect::route('users/groups')->withFlashMessage('Group Created Successfully.');
then on your view page,
#if (Session::has('flash_message'))
{{ Session::get('flash_message') }}
#endif
Method 2 is much cleaner and does not require additional code under create().

{{ Session::get('success') }}
This just echos the session variable 'success'. So when you use
{{ Session::get('success') }}
#if($success)
<div class="alert-box success">
<h2>{{ $success }}</h2>
</div>
#endif
you are seeing it's output along with the error of the next statement. Because with() function only sets the value in Session and will not set as a variable. Hence #if($success) will result in undefined variable error.
As #Andreyco said,
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif
This should work.
The reason you are not seeing it might be because the action you are performing is not success. And this does not require you to either reinstall xampp or modify php.ini.

Laravel 4.2
Personally i use
Session::flash('key', 'value');
return Redirect::to('some/url');
then in the view id first check if there is a session of that key in the view
#if(Session::has('key'))
{{Session::get('key')}} //this prints out the message or your 'value' in the session::flash method
#endif
it works for me most of the time and i usually have that blade template integrated into my view just so i can push success messages to the view from my codes.
please do note that it is stated in the documentation that "Sometimes you may wish to store items in the session only for the next request. You may do so using the Session::flash method" so yes it expires after the next page.
hope this helps

i just realized in using the Redirect::to(), when you use the withInput() method, chaining a with() function to pass variables will not work. the only way is either you flash your inputs separately using Input::flash(), and use the with() to pass your variables or you pass your variable via session using Session::flash('key','val') and retrieve in the view via session::get('key').

This link describes how to do this http://vegibit.com/flash-messages-in-laravel/
Just tried with laravel 5 - works to me.

Inside of the routes.php file try to create your routes within the
Route::group(['middleware' => ['web']], function () {
//routes here
}
then use
#if(Session::has('success'))
<div class="alert-box success">
<h2>{{ Session::get('success') }}</h2>
</div>
#endif

I fixed mine by changing the session driver in config/session.php from array to file !

Related

Undefined variable: categories in user.blade.php

I was trying to extend my user.blade.php to my views menu.blade.php. Everything works fine with my other views that use the same user.blade.php too. But not with my menu.blade.php, I get an error saying "Undefined variable: categories (View: D:\xampp\htdocs\mieaceh\resources\views\layouts\user.blade.php)" with "Possible typo $categories
Did you mean $errors?"
Here are the codes to my user.blade.php
#foreach($categories as $category)
<a href="{{ route('menu.index', ['category' => $category->slug]) }}">
<div class="card-category" style="width: 10rem; height: 4rem;">
{{ $category->name }}
</div>
</a>
#endforeach
How do I solve it?
If you want to make a piece of view that appears in multiple places, you can use blade components https://laravel.com/docs/8.x/blade#components.
This will help encapsulating this partials behavior and required data.

isset is not working in laravel

I am sending a variable from controller to a view.
$message = "Thanks for Contacting";
return redirect('services')->with($message);
HTML
#isset ($message)
<a style="color: red;"> {{$message}} </a>
#endisset
But it shows en error, because when the first services is loaded from this route
Route::get('/services', function () {
return view('services');
});
There's no variable,so it gives en error. Please let me know what I am missing?
The problem is how you're passing the variable to your view.
the correct way is:
return view('services')->with('message', $message);
or
return view('services')->withMessage($message);
or
return view('services', ['message' => $message]);
or
return view('services', compact('message'));
You have to use it with #if,
Try this:
#if(session()->has('message'))
<a style="color: red;"> {{ session('message')}} </a>
#endif
and also change your controller like this:
return redirect('services')->with('message', $message);
The variable that set in redirect()->with() will saved to sessions variable, so to access it just call session() helper. Example:
#if (session('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
More explanation:
https://laravel.com/docs/5.6/redirects#redirecting-with-flashed-session-data

Is it possible to delete record without using forms in laravel 5.4

I want to delete a record but I haven't been successful, apparently my code is wrong. Solutions i came across say i have to use a post in my form method and add the method_field helper. This would mean my view having a form in it, i want to avoid this if possible. Is it then possible to do my delete another way. Below is my code
snippet of my view
<div class="backbtn">
<a class="btn btn-savvy-delete" href="/tasks/{{$task->id}}" data-toggle="tooltip" title="Delete"><i class="fa fa-trash-o" aria-hidden="true"> Delete</i></a>
</div>
<div class="panel-body">
<p><strong>Owner:</strong> {{ ucfirst($task->employee->firstname) }} {{" "}} {{ ucfirst($task->employee->lastname) }}</p>
<p><strong>Task:</strong> {{ $task->title }}</p>
<p><strong>Description:</strong> {{ $task->description }}</p>
</div>
TaskController
public function destroy($id)
{
Task::destroy($id);
Session::flash('status', "Task was successfully deleted.");
return redirect('/tasks');
}
web.php
Route::delete('/tasks/{id}', 'TaskController#delete');
Im not sure what error you are getting, but i can point out a few things. For one use Route::get instead of ::delete, you are calling it via a link not a form method.
Secondly to delete follow what the laravel doc says here eg.
$task = App\Task::find(1);
$task->delete();

Laravel 4 return messages

Apologies Laravel newbee - on the learning curve.
In my controller I have
return Redirect::to('admin/categories/index')
->with('message', 'something went wrong');
How do I display this in my blade template? Are these known as 'flash messages'?
That is known as a redirect with flash data.
return Redirect::to('admin/categories/index')
->with('message', 'something went wrong');
With method flashes data to the session, you can retrieve it using Session::get in your View
#if(Session::has('message'))
<div class="alert-box success">
<h2>{{ Session::get('message') }}</h2>
</div>
#endif
I use this:
#if ( Session::has('message') )
<p class="alert">{{ Session::get('message') }}</p>
#endif
on the header of my base.blade.php

Laravel Redirect Back with() Message

I am trying to redirect to the previous page with a message when there is a fatal error.
App::fatal(function($exception)
{
return Redirect::back()->with('msg', 'The Message');
}
In the view trying to access the msg with
Sessions::get('msg')
But nothing is getting rendered, am I doing something wrong here?
Try
return Redirect::back()->withErrors(['msg' => 'The Message']);
and inside your view call this
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
Laravel 5 and later
Controller
return redirect()->back()->with('success', 'your message,here');
Blade:
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
Alternative approach would be
Controller
use Session;
Session::flash('message', "Special message goes here");
return Redirect::back();
View
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
In Laravel 5.4 the following worked for me:
return back()->withErrors(['field_name' => ['Your custom message here.']]);
You have an error (misspelling):
Sessions::get('msg')// an extra 's' on end
Should be:
Session::get('msg')
I think, now it should work, it does for me.
Just set the flash message and redirect to back from your controller functiion.
session()->flash('msg', 'Successfully done the operation.');
return redirect()->back();
And then you can get the message in the view blade file.
{!! Session::has('msg') ? Session::get("msg") : '' !!}
In Laravel 5.5:
return back()->withErrors($arrayWithErrors);
In the view using Blade:
#if($errors->has())
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
In laravel 5.8 you can do the following:
return redirect()->back()->withErrors(['name' => 'The name is required']);
and in blade:
#error('name')
<p>{{ $message }}</p>
#enderror
For Laravel 5.5+
Controller:
return redirect()->back()->with('success', 'your message here');
Blade:
#if (Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{{ Session::get('success') }}</li>
</ul>
</div>
#endif
in controller
For example
return redirect('login')->with('message',$message);
in blade file
The message will store in session not in variable.
For example
#if(session('message'))
{{ session('message') }}
#endif
I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:
Pull in the package through Composer.
"require": {
"laracasts/flash": "~1.0"
}
Include the service provider within app/config/app.php.
'providers' => [
'Laracasts\Flash\FlashServiceProvider'
];
Add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => 'Laracasts\Flash\Flash'
];
Pull the HTML into the view:
#include('flash::message')
There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.
optional changes:
If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:
#if (Session::has('flash_notification.message'))
<div class="{{ Session::get('flash_notification.level') }}">
{{ Session::get('flash_notification.message') }}
</div>
#endif
If you would like to view the HTML pulled in by #include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.
If you need to modify the partials do:
php artisan view:publish laracasts/flash
The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.
Here is the 100% solution
*Above mentioned solutions does not works for me but this one works for me in laravel 5.8:
$status = 'Successfully Done';
return back()->with(['status' => $status]);
and receive it as:
#if(session()->has('status'))
<p class="alert alert-success">{{session('status')}}</p>
#endif
It works for me and Laravel version is ^7.0
on Controller
return back()->with('success', 'Succesfully Added');
on Blade file
#if (session('success'))
<div class="alert alert-success">
{!! session('success') !!}
</div>
#endif
For documentation look at Laravel doc
I know this is an old post but this answer might help somebody out there.
In Laravel 8.x this is what worked for me: You can return the error to the previous page or to another page.
return Redirect::back()->withErrors(['password' => ['Invalid Username or Password']]);
This will also work:
return view('auth.login')->withErrors(['username' => ['Invalid Username or Password']]);
Please ENSURE, however, that the page/view you are returning has a field name that corresponds to the first parameter passed in the withErrors method (in this case, username or password) and that the #error directive in your view references the same field like this
#error('password') //or #error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
for example
Hope this helps somebody. Cheers.
#Laravel-9
Inside the blade where this redirection back action initiated
return redirect()->back()->with('message', "The Message");
Inside the blade where this form, will be returned after the above action
#if(session()->has('message'))
<p class="alert alert-success"> {{ session()->get('message') }}</p>
#endif
For laravel 5.6.*
While trying some of the provided answers in Laravel 5.6.*, it's clear there has been some improvements which I am going to post here to make things easy for those that could not find a solution with the rest of the answers.
STEP 1:
Go to your Controller File and Add this before the class:
use Illuminate\Support\Facades\Redirect;
STEP 2:
Add this where you want to return the redirect.
return Redirect()->back()->with(['message' => 'The Message']);
STEP 3:
Go to your blade file and edit as follows
#if (Session::has('message'))
<div class="alert alert-error>{{Session::get('message')}}</div>
#endif
Then test and thank me later.
This should work with laravel 5.6.* and possibly 5.7.*
I faced with the same problem and this worked.
Controller
return Redirect::back()->withInput()->withErrors(array('user_name' => $message));
View
<div>{{{ $errors->first('user_name') }}}</div>
In blade
#if(Session::has('success'))
<div class="alert alert-success" id="alert">
<strong>Success:</strong> {{Session::get('success')}}
</div>
#elseif(session('error'))
<div class="alert alert-danger" id="alert">
<strong>Error:</strong>{{Session::get('error')}}
</div>
#endif
In controller
for success
return redirect()->route('homee')->with('success','Successfully Log in ');
for error
return back()->with('error',"You are not able to access");
laravl 8
Route::post('/user/profile', function () {
// Update the user's profile...
return redirect('/dashboard')->with('status', 'Profile updated!');
});
Blade syntax
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
enter link description here
For Laravel 3
Just a heads up on #giannis christofakis answer; for anyone using Laravel 3 replace
return Redirect::back()->withErrors(['msg', 'The Message']);
with:
return Redirect::back()->with_errors(['msg', 'The Message']);
Laravel 5.6.*
Controller
if(true) {
$msg = [
'message' => 'Some Message!',
];
return redirect()->route('home')->with($msg);
} else {
$msg = [
'error' => 'Some error!',
];
return redirect()->route('welcome')->with($msg);
}
Blade Template
#if (Session::has('message'))
<div class="alert alert-success" role="alert">
{{Session::get('message')}}
</div>
#elseif (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
Enyoj
I got this message when I tried to redirect as:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request)
->withInput();
When the right way is:
public function validateLogin(LoginRequest $request){
//
return redirect()->route('sesion.iniciar')
->withErrors($request->messages())
->withInput();
Laravel 5.8
Controller
return back()->with('error', 'Incorrect username or password.');
Blade
#if (Session::has('error'))
<div class="alert alert-warning" role="alert">
{{Session::get('error')}}
</div>
#endif
**Try This**
Try This Code
--- Controller ---
return redirect('list')->with('message', 'Successfully');
return redirect('list');
---- Blade view ------
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif

Resources