こなさんち

しがないフリーランスエンジニアの備忘録。

LaravelCollectiveにカスタム関数追加してやったぞ @Laravel5.4

概要

HTMLにAnchor吐き出す関数なかったな。 →作るか

1. artisan

php artisan make:provider HtmlServiceProvider

2.その中身

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Html;

class HtmlServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        Html::macro('anchor', function ($text, $attrs = '') {
            $anc = '<a' ;
            
            if (is_array($attrs)){
                foreach($attrs as $key => $value) {
                    $anc .= ' ' . $key . '=\'' . $value . '\'';
                }
                
            } else {
                $anc .= $attrs;
            }
            
            $anc .= '>' . $text . '</a>';
            return $anc;
        });
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

3. app.phpに追加

<?php

//略
    'aliases' => [

//略
        
        // Custom Function
        'CostomHelper' => 'app\lib\CostomHelper',

    ],

4. Usage

<?php

{!! Html::anchor('<i class="ban icon"></i>パスワードを忘れた場合', ['href' => '/user/forgot', 'class' => 'ui negative basic button']) !!}

5.おわり

もう今日は頑張らない