2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravel】toastrを使って、フラッシュメッセージを表示する

Posted at

今回は、フラッシュメッセージをフワッと表示する方法を記載します。

使用環境

Laravel 6.2

フラッシュメッセージとは?

簡単に言うと、セッションに一時的に保存して、表示するものです。
ステータスメッセージなどに使われます。

Laravelでは、flashメソッドなるものが用意されています。

使い方

書き方は、いろいろあります。

session()->flash('message','作成しました');

または、

return view('index')->with('message','作成しました');

とかです。

これで、デフォルトのフラッシュメッセージは表示されるようになったかと思います。

今回は、toastr.jsというものを使い、以下のようにするためにしていきます。
スクリーンショット 2021-06-17 16.53.16.png

1,スクリプトを読み込む

toastr.jsを使うために、以下をviewに読み込みます。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

2,viewファイルの作成

適当にviewを作成します。そこに記載します。

toastr.blade.php
@if(session('message'))
<script>
$(function(){
  toastr.success('{{session("message")}});
});
</script>
@endif

""をつけ忘れたおかげで、めちゃめちゃ苦労しました。。。

これをレイアウトのファイルにinclude()することで使えるようになります。

3,オプションの設定

また、画面の中央部に表示したいなどは、オプションをつけましょう。

toastr.blade.php
toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "positionClass": "toast-top-center",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "300",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
          }

オプションは、色々いじれます。
以下のサイトを参考にしてください。
https://codeseven.github.io/toastr/demo.html

参考

https://qiita.com/n_oshiumi/items/17753aa6237c7afbbe09
https://qiita.com/usaginooheso/items/6a99e565f16de2f9ddf7

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?