Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4 Show flash error and success messages in different ways

Tags:

laravel

Method from my PostController

public function store(PostRequest $request)
    {
        if (Post::create($request->all())) {
            $request->session()->flash('status', 'Post was successfully added!');
        } else {
            $request->session()->flash('status', 'Error!');
        }
        return redirect('/');
    }

index view

<?php if(session()->has('status')){
        echo '<div style="text-align: center">';
        echo session()->get('status');
        echo '</div>';
    }?>

How to show error and success messages in different ways?

like image 870
Heidel Avatar asked Mar 22 '17 17:03

Heidel


3 Answers

You can use something like this:

public function store(PostRequest $request) {
    if (Post::create($request->all())) {
        $request->session()->flash('message.level', 'success');
        $request->session()->flash('message.content', 'Post was successfully added!');
    } else {
        $request->session()->flash('message.level', 'danger');
        $request->session()->flash('message.content', 'Error!');
    }
    return redirect('/');
}

In your blade file:

@if(session()->has('message.level'))
    <div class="alert alert-{{ session('message.level') }}"> 
    {!! session('message.content') !!}
    </div>
@endif

The code above uses bootstrap's alert css classes for styling and is inspired by Jeffrey Way's Laracasts Flash package

like image 58
Paras Avatar answered Oct 30 '22 16:10

Paras


You can display flash messages in this way:

In your controller:

$request->session()->flash('success', 'Record successfully added!');
//OR
$request->session()->flash('warning', 'Record not added!');

In your veiw:

@foreach (['danger', 'warning', 'success', 'info'] as $key)
 @if(Session::has($key))
     <p class="alert alert-{{ $key }}">{{ Session::get($key) }}</p>
 @endif
@endforeach
like image 14
Muhammad Shahzad Avatar answered Oct 30 '22 17:10

Muhammad Shahzad


  1. Write code like this in your Blade template:

    @if(Session::has('error'))
        <p class="alert alert-danger">{{ Session::get('error') }}</p>
    @endif
    
  2. Write code like this in your Controller:

    Session::flash('error', 'Some thing is wrong. Please try again');
    Redirect::to(path to blade file route);
    
like image 1
Madhav Kankraan Avatar answered Oct 30 '22 18:10

Madhav Kankraan