4
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.

ヘルパ関数の自作 by Laravel

Last updated at Posted at 2020-01-13

helperでフラッシュメッセージ関数作成したんで備忘録

helpers.php
<?php
if (! function_exists('set_message')) {
    function set_message($msg = null, $is_success = true) {
        session()->flash('message', $msg);
        session()->flash('is_success', $is_success);
    }
}
composer.json
"autoload": {
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php"//追加
    ]
},
console
$ composer dump-autoload

レイアウトに設定しておく。

layout.blade.php
@if (session('message'))                                               
    @if (session('is_success'))                                        
        <div class="alert alert-success">{{ session('message') }}</div>
    @else                                                              
        <div class="alert alert-danger">{{ session('message') }}</div> 
    @endif                                                             
    <?php
    session()->flash('message', null);                        
    session()->flash('is_succes', null);
    ?>
@endif                                                                 

使用例

xxxController
//どこからでも使用可能
public function add() {
    $item_id = session('id');
    if (isset($item_id)) {
        if ((new Cart)->addDb($item_id, 1))
            //正常メッセージ
            set_message('商品をカートに入れました');
        } else {
            //エラーメッセージ
            set_message('在庫が足りません', false);
        }
    }
    session()->forget('id');
    return $this->index();
}

参考サイト
Laravel 5へ自作のヘルパー関数を追加するベストプラクティス

4
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
4
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?