Laravel 6 Flash Message Tutorial (ok)

https://www.itsolutionstuff.com/post/laravel-6-flash-message-tutorialexample.html

Ví dụ 1:

<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) }} <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></p>
      @endif
    @endforeach
  </div> <!-- end .flash-message -->

Ví dụ 2:

ol

C:\xampp\htdocs\reset\routes\web.php

<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */
use App\Http\Controllers\HomeController;
use App\Http\Controllers\ItemController;
Route::get('/', function () {
  dd('Welcome to simple user route file.');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('/test', [ItemController::class, 'index'])->name('test.index');
Route::post('/test', [ItemController::class, 'store'])->name('test.store');

C:\xampp\htdocs\reset\app\Http\Controllers\ItemController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Item;
class ItemController extends Controller {
  public function index() {
    return view('test');
  }
  public function store(Request $request) {
    $this->validate($request, [
      'title'   => 'required',
      'details' => 'required',
    ]);
    $items = Item::create($request->all());
    // return back()->with('success', 'Item created successfully!');
    return redirect()->route('test.index')->with('success','You have no permission for this page!');
  }
  // public function store(Request $request) {
  //   $this->validate($request, [
  //     'title'   => 'required',
  //     'details' => 'required',
  //   ]);
  //   $items = Item::create($request->all());
  //   return back()->with('error', 'Item created successfully!');
  // }
  // public function store(Request $request) {
  //   $this->validate($request, [
  //     'title'   => 'required',
  //     'details' => 'required',
  //   ]);
  //   $items = Item::create($request->all());
  //   return back()->with('warning', 'Item created successfully!');
  // }
  // public function store(Request $request) {
  //   $this->validate($request, [
  //     'title'   => 'required',
  //     'details' => 'required',
  //   ]);
  //   $items = Item::create($request->all());
  //   return back()->with('info', 'Item created successfully!');
  // }
}

C:\xampp\htdocs\reset\resources\views\flash-message.blade.php

@if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
  <strong>{{ $message }}</strong>
</div>
@endif
@if ($message = Session::get('error'))
<div class="alert alert-danger alert-block">
  <button type="button" class="close" data-dismiss="alert">×</button>
  <strong>{{ $message }}</strong>
</div>
@endif
@if ($message = Session::get('warning'))
<div class="alert alert-warning alert-block">
  <button type="button" class="close" data-dismiss="alert">×</button>
  <strong>{{ $message }}</strong>
</div>
@endif
@if ($message = Session::get('info'))
<div class="alert alert-info alert-block">
  <button type="button" class="close" data-dismiss="alert">×</button>
  <strong>{{ $message }}</strong>
</div>
@endif
@if ($errors->any())
<div class="alert alert-danger">
  <button type="button" class="close" data-dismiss="alert">×</button>
  Please check the form below for errors
</div>
@endif

C:\xampp\htdocs\reset\resources\views\test.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="{{ url('css/app.css') }}" rel="stylesheet">
</head>
<body>
  <div id="app" class="container">
    @include('flash-message')
    <form action="{{ route('test.store') }}" method="post" accept-charset="utf-8">
      @csrf
       <legend>Form Register</legend>
      <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" name="title" id="title" placeholder="Title field">
      </div>
      <div class="form-group">
        <label for="details">Details</label>
        <input type="text" class="form-control" name="details" id="details" placeholder="Input field">
      </div>
      <button type="submit" class="btn btn-primary">Submit</button>
    </form>
  </div>
  <script src="{{ url('js/app.js') }}"></script>
</body>
</html>

C:\xampp\htdocs\reset\app\Models\Item.php

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Item extends Model {
  use HasFactory;
  protected $fillable = [
    'title',
    'details'
  ];
}

C:\xampp\htdocs\reset\database\migrations\2022_05_13_085619_create_items_table.php

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateItemsTable extends Migration {
  /**
   * Run the migrations.
   *
   * @return void
   */
  public function up() {
    Schema::create('items', function (Blueprint $table) {
      $table->id();
      $table->string("title");
      $table->string("details");
      $table->timestamps();
    });
  }
  /**
   * Reverse the migrations.
   *
   * @return void
   */
  public function down() {
    Schema::dropIfExists('items');
  }
}

Laravel 6 Flash Message Tutorial

By Hardik Savani September 19, 2019 Category : LaravelPlayUnmuteLoaded: 1.15%FullscreenVDO.AIHi Developer,

In this example, i would like to show you how to create flash message notification in laravel 6. you can create laravel 6 flash message without composer package. i write step by step tutorial for laravel 6 flash message from controller.

we will define various type of flash message notification like alert success, alert danger, alert info, alert warning messages in bootstrap laravel 6 projects. When you have success task on controller method then you can use success flash message, if you have any error task then you can use error flash message.

Flash messages are required in laravel 6 application because that way we can give alter with what progress complete, error, warning etc. In this tutorial, I added several ways to give a flash message like redirect with success message, redirect with an error message, redirect with a warning message and redirect with info message. In this example, we use a bootstrap flash alert layout that way it becomes good layout.

So, you have to just follow the basic three step to integrate flash message in your laravel 6 application. So let's follow below step:

Step 1: Create Global File For Flash Message

In first step we will create new blade file flash-message.blade.php. In this file we will write code of bootstrap alert and check which messages come.

There are following alert will added:

1)success

2)error

3)warning

4)info

5)validation error

So, let's create flash-message.blade.php file and put bellow code on that file.

resources/views/flash-message.blade.php

@if ($message = Session::get('success'))<div class="alert alert-success alert-block">    <button type="button" class="close" data-dismiss="alert">×</button>        <strong>{{ $message }}</strong></div>@endif  @if ($message = Session::get('error'))<div class="alert alert-danger alert-block">    <button type="button" class="close" data-dismiss="alert">×</button>        <strong>{{ $message }}</strong></div>@endif   @if ($message = Session::get('warning'))<div class="alert alert-warning alert-block">    <button type="button" class="close" data-dismiss="alert">×</button>        <strong>{{ $message }}</strong></div>@endif   @if ($message = Session::get('info'))<div class="alert alert-info alert-block">    <button type="button" class="close" data-dismiss="alert">×</button>        <strong>{{ $message }}</strong></div>@endif  @if ($errors->any())<div class="alert alert-danger">    <button type="button" class="close" data-dismiss="alert">×</button>        Please check the form below for errors</div>@endif

Step 2: Use Flash Message in Theme

In this step we have to just include flash-message.blade.php file in your theme default file. You have to just include this flash file in your default theme blade file like as bellow:

@include('flash-message')

You can also see i added flash file on my theme, so you can add that way. Let's see bellow example:

resources/views/layouts/app.blade.php

<!DOCTYPE html><html lang="en"><head>    <meta charset="utf-8">    <meta http-equiv="X-UA-Compatible" content="IE=edge">    <meta name="viewport" content="width=device-width, initial-scale=1">    <!-- Styles -->    <link href="/css/app.css" rel="stylesheet"></head><body>    <div id="app">        @include('flash-message')        @yield('content')    </div>    <!-- Scripts -->    <script src="/js/app.js"></script></body></html>

Read Also: Laravel 6 CRUD Application Tutorial

Step 3: Use Flash Messages with Redirect

In this step we will learn how to give message when you redirect one by one:

1. Redirect with success message

We can simple redirect route or redirect url or redirect back with success flash message, we can use in controller like this way:

public function create(Request $request){	$this->validate($request,[        'title' => 'required',        'details' => 'required'        ]);	$items = Item::create($request->all());	return back()->with('success','Item created successfully!');}

You can get layout of success flash message:

2. Redirect with error message

We can simple redirect route or redirect url or redirect back with error flash message, we can use in controller like this way:

public function create(Request $request){    return redirect()->route('home')        ->with('error','You have no permission for this page!');}

You can get layout of error flash message:

3. Redirect with warning message

We can simple redirect route or redirect url or redirect back with warning flash message, we can use in controller like this way:

public function create(Request $request){    return redirect()->route('home')            ->with('warning',"Don't Open this link");}

You can get layout of warning flash message:

4. Redirect with info message

We can simple redirect route or redirect url or redirect back with info flash message, we can use in controller like this way:

public function create(Request $request){    $this->validate($request,[        'title' => 'required',        'details' => 'required'        ]);    $items = Item::create($request->all());    return back()->with('info','You added new items, follow next step!');}

You can get layout of info flash message:

5. Validation Error

If you use laravel 5 validation then you will redirect back with errors automatically, At that time it will also generate error flash message.

Read Also: Laravel 6 Ajax Request Example

public function create(Request $request){    $this->validate($request,[        'title' => 'required',        'details' => 'required'        ]);    .....}

You can get layout of error flash message:

This way you can simple implement flash message in your laravel 6 application.

I hope it can help you....

Last updated