Laravel Bladeで使える独自関数を定義するには?

ショコラ
ショコラ

Laravel Bladeで使える独自関数を定義するには?

ブレード側でもコントローラー側でも使える独自関数を定義してみます。

もっさん先輩
もっさん先輩

手順

Bladeで使える独自関数を定義する手順

  1. 独自関数を app/Libs/functions.php に定義します。ディレクトリ、ファイル名は任意です。どこでも構いません。
mkdir app/Libs

配置先:app/Libs/functions.php

@config、@urlディレクティブ を使うには、以下の _config、_url関数が必要です。

<?php
function numf($val):string
{
  return is_numeric($val) ? number_format((float)$val) : '';
}

function formatDate($expr,$format):string
{
  return date($format,strtotime($expr));
}

function headline($str,$width = 20)
{
  $headline = $str;
  if (mb_ereg("(.+?)(。|\n)",$str,$m)) {
    $headline = $m[1];
  }
  return mb_strimwidth($headline,0,$width);
}

function flash($key, $message = null)
{
  if (!is_null($message))
    session()->flash($key,$message);
  return session($key);
}

function render_blade(string $blade)
{
  $tmpl = uniqid();
  $file = resource_path('views/dynamic/'.$tmpl.'.blade.php');
  try {
    file_put_contents($file,$blade);
    return view('dynamic.'.$tmpl)->render();
  }
  finally {
    unlink($file);
  }
}

function _config(string $key, $default = null)
{
  return config($key) ?: env($key) ?: $default;
}

function _url(string $route = '', string $param = '')
{
  if (str_starts_with($route,'/'))
    [$route,$param] = ['',$route.$param];

  static $cache = [];
  if (!isset($cache[$route]))
    if (\Route::has($route))
      $cache[$route] = route($route);
    elseif ('' == $route)
      $cache[$route] = _config('APP_URL','//'.$_SERVER['HTTP_HOST']);
    elseif ('' != ($cache[$route] = _config($route)))
      ;
    else {
      [$route,$param] = ['','/'.$route.$param];
      $cache[$route] = _url($route);
    }

  return $cache[$route].$param;
}
  1. composer.json の autoload で↑上で作成したファイルを読み込むようにします。
"autoload": {
  "files":["app/Libs/functions.php"]
}
  1. composer.json を変更した後は、「composer dumpautoload」コマンドで反映します。忘れないように。
composer dumpautoload

sail の場合は↓こちらです。

sail composer dumpautoload
  1. ブレードで関数を使用します。コントローラー側でも独自関数を使用できます。
{{ numf(9999) }}

以上

Scroll to Top