Custom Helper Laravel h??ng d?n c?ch t?o custom helper trong Laravel

Custom Helper Laravel h??ng d?n c?ch t?o custom helper trong Laravel

Trong Laravel có r?t nhi?u Helper Function, nh?ng n?u nh? v?y v?n ch?a ?? và b?n mu?n t?o custom helper laravel ?? dùng cho tác v? nào ?ó trong project thì b?n có th? tham kh?o bài vi?t này.

H??ng d?n t?o Custom Helper Laravel cách 1

N?u project c?a b?n ch?a có th? m?c Helpers thì t?o theo ???ng d?n: app\Helpers

Trong th? m?c Helpers, t?o file Helper c?a b?n, ví d?: app\Helpers\MyHelper.php

<?php

namespace App\Helpers;

/**
 * My Helper
 */
class MyHelper
{
	
	public static function test()
	{
		$result = 'My Custom Helper';

		return $result;
	}
}

Khai báo Helper m?i t?o trong: config/app.php

    'aliases' => Facade::defaultAliases()->merge([
        // 'ExampleClass' => App\Example\ExampleClass::class,
        'MyHelper' => App\Helpers\MyHelper::class
    ])->toArray(),

Ch? ??n gi?n v?y thôi, và gi? m?i khi b?n c?n dùng trong controller thì khai báo và dùng nh? sau:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Helpers\MyHelper;

class Testcontroller extends Controller
{
    public function index()
    {
        $data = MyHelper::test();

        return view('test.index')->with(['data' => $data]);
    }
}

N?u dùng custom helper trong view thì dùng tr?c ti?p, không c?n khai báo

T?o Custom Helper trong Laravel cách 2

T??ng t? nh? cách 1, t?o file helper c?a b?n trong th? m?c Helpers, vd: app\Helpers\YourHelper.php

<?php 

if(!function_exists('testFunction')){
	
	function testFunction() 
	{
	    $result = 'Your Custom Helper';
	    
	    return $result;
	}
}

Trong th? m?c g?c c?a project laravel, m? file composer.json, tìm ??n ph?n autoload và khai báo file helper v?a t?o, t??ng t? nh? sau:

    "autoload": {
        "psr-4": {
           // ...
        },
        "files": [
            "app/Helpers/YourHelper.php"
        ]
    },

Sau ?ó ch?y l?nh composer ?? c?p nh?t autoload:

composer dump-autoload

Done, v?i cách 2 có th? dùng helper function tr?c ti?p trong controller view… mà không c?n khai báo

vd:

$data = testFunction();

L?i k?t

V?y là bài vi?t này mình ?ã gi?i thi?u 2 cách t?o custom helper trong laravel, n?u b?n có cách nào khác thì ?? l?i comment nhé.

5 4 đánh giá
Đánh giá bài viết
Theo dõi
Thông báo của
guest

0 Góp ý
Phản hồi nội tuyến
Xem tất cả bình luận