Flash messaging in laravel

Flash massages is a medium of communicate to the user. Its just something the user intended to do or some information appears by application.

Let's see example of flash messages :

<?php
Route::get('default', function(){
    return view('default');
});
Route::get('flash', function(){
    return Redirect::to('default')->with('message','This is my flash message');
});

there are routes are defined.

1. flash route : Redirecting to default route and also generating a message for passing

2.default route : This time the flash message is passing through default route to default.blade.php page.

Create new view file default.blade.php

<?php use Illuminate\Support\Facades\Session; ?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title of the document</title>
</head>
<body>
    {!! Session::get('message') !!}        
<br>    This is default page
</body>
</html>

Test above code:

Put url yourmachinename/flash to your browser address bar. After press enter, Url will immediately redirected to yourmachinename/default.

You will see a flash message This is my flash message with others body part of default view page.

 

Passing flash messages through controllers :

Check my Controller bookController. There are add record, update record and delete record flash messages are passes through controller methods.

<?php

class BookController extends Controller{
    public function store(PublishBookRequest $requestData)
	{
        $book = new Book;
        $book->title= $requestData['title'];
        $book->description= $requestData['description'];
        $book->author= $requestData['author'];
        $book->save();

        //Flash message for add new record
        return redirect()->route('book.index')->with('message', 'New record has been added!');
	}

	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id, PublishBookRequest $requestData)
	{
        $book = Book::find($id);

        $book->title = $requestData['title'];
        $book->description = $requestData['description'];
        $book->author = $requestData['author'];
	    $book->save();

        //Flash message for update record
	    return redirect()->route('book.index')->with('message', 'Record has been updated!');
	}
	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
    {
        Book::find($id)->delete();

        //Flash message for delete record
        return redirect()->route('book.index')->with('message', 'Record deleted successfully!');
    }
}

 

View section :

@if(Session::has('message'))
        <div class="alert alert-info messageBox" id="myModal" >{!! Session::get('message') !!}</div>
@endif

Place above code in view section. You can control flash messages with the use of client side languages like css bootstrap or jquery. 

Something to say? Tell us in comment section.