Laravelで共通処理を書く
2024.04.09 09:00
2024.04.08 22:27

Laravelのアプリ全体で使う便利関数のようなものを作ってみました。今回は、URLを含んだテキストを自動でリンクさせる処理にします。
まずこの共通処理を「Helper」とし、以下の場所にファイルを作ります。
app/Helpers/TextHelper.php
中身はこんな感じです。
<?php
if (! function_exists('makeLink')) {
function makeLink(string $text): string
{
$pattern = '/((?:https?|ftp):\/\/[-_.!~*\'()a-zA-Z0-9;\/?:@&=+$,%#]+)/';
$replace = '<a href="$1" target="_blank" class="text-accent hover:text-accent_light hover:underline">$1</a>';
$text = preg_replace($pattern, $replace, htmlspecialchars($text));
return $text;
}
}
文字列を受け取り、その中にURLがあれば正規表現でリンクをつけて返します。
次にcomposer.jsonに読み込み先を追記します。
"autoload": {
"psr-4": {
"App\\": "app/",
"Tests\\": "tests/"
},
"files": [
"app/Helpers/TextHelper.php"
]
},
コマンドラインからcomposerを再読込します。
composer dump-autoload
これで準備は完了です。あとはどこでもこんな感じで使えます。
makeLink('文字列を入れます。https://hogehoge.co.jpへアクセス');
今回は以上です!