Laravel 5.4 สร้าง Helper ไว้ใช้งาน

บางท่านอยากมี Function ซักตัวหนึ่งไว้เรียกใช้ โดย Function สามารถใช้ได้ทุกทีทีเราอยากใช้ วันนี้ผมจะมานำเสนอ Helper.php ไว้สำหรับเรียกใช้ Function กันครับ

สร้างไฟล์ Helper.php

ให้เราสร้างไฟล์ php ในโฟลเดอร์ app หรือที่ไหนก็ได้ที่เราจะเรียกใช้มัน โดยที่ไฟล์ Helper.php ของผมจะมี Function ตัวหนึ่งไว้สำหรับ Format วันที่ให้เป็นเวลาไทย ดังนี้

<?php

function formatDateThat($strDate)
{
$strYear = date("Y",strtotime($strDate))+543;
$strMonth= date("n",strtotime($strDate));
$strDay= date("j",strtotime($strDate));
$strHour= date("H",strtotime($strDate));
$strMinute= date("i",strtotime($strDate));
$strSeconds= date("s",strtotime($strDate));
$strMonthCut = Array("","ม.ค.","ก.พ.","มี.ค.","เม.ย.","พ.ค.","มิ.ย.","ก.ค.","ส.ค.","ก.ย.","ต.ค.","พ.ย.","ธ.ค.");
$strMonthThai=$strMonthCut[$strMonth];
return "$strDay $strMonthThai $strYear $strHour:$strMinute";
}

จาก Code ด้านบนเป็นตัวอย่าง Code ง่ายๆ ไว้สำหรับ Format วันเดือนปี เป็นภาษาไทยเบื้องต้น

ทำการ Autoload Composer

หลังจากที่เราสร้างไฟล์ Helper.php เสร็จแล้วให้ไปยังไฟล์ composer.json และทำการเพิ่มโค้ดต่อไปนี้

"autoload": {
"classmap": ["database"],
"psr-4": {"App\\": "app/"},
"files" : ["app/Helper.php"] <-- เพิ่มส่วนนี้เป็นตำแหน่งที่ไฟล์ Helper อยู่
}

หลังจากนั้น run คำสั่ง cmd เป็นอันเสร็จ

composer dumpautoload

วิธีใช ้Function ของ Helper

ถ้าเราเรียกใช้ในไฟล์ php สามารถเรียกใช้ได้ตรงๆ เลย

$dateThai = formatDateThai( date("Y-m-d H:i:s"));

ถ้าเรียกใช้ใน Blade

{{ formatDateThai( date("Y-m-d H:i:s")) }}

หวังว่าจะมีประโยชน์ต่อผู้อ่านทุกท่านนะครับ วันนี้ขอจบเพียงเท่านี้ครับ :)

credit: https://medium.com/teknomuslim/how-to-create-helper-functions-in-laravel-d769d12218d4

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade