4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

laravel ディレクティブ @injectを使ってサービスクラスなどのメソッドをビューで読み込む

Posted at

目的

  • 数多くあるディレクティブの一つである@injectを使ってサービスクラスなどのメソッドをビューファイルで使う方法をまとめる

環境

  • ハードウェア環境
項目 情報
OS macOS Catalina(10.15.5)
ハードウェア MacBook Pro (13-inch, 2020, Four Thunderbolt 3 ports)
プロセッサ 2 GHz クアッドコアIntel Core i5
メモリ 32 GB 3733 MHz LPDDR4
グラフィックス Intel Iris Plus Graphics 1536 MB
  • ソフトウェア環境
項目 情報 備考
PHP バージョン 7.4.8 Homebrewを用いてこちらの方法で導入→Mac HomebrewでPHPをインストールする
Laravel バージョン 8.X commposerを用いてこちらの方法で導入→Mac Laravelの環境構築を行う
MySQLバージョン 8.0.19 for osx10.13 on x86_64 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでMySQLをインストールする
Node.jsバージョン v12.14.1 Homwbrewを用いてこちらの方法で導入→Mac HomebrewでNode.jsをインストールする

情報

  • 「環境」に記載したものと同様の環境をMacに直接構築して本記事用に動作確認を行った。

方法

  • bladeファイルで下記のように@injectディレクティブを使用してメソッドを呼び出す。

    foo.blade.php
    @inject('クラスを注入する変数名', 'namespaceを含むクラス名')
    
    {{ $クラスを注入する変数名->呼び出すメソッド名() }}
    

  • 下記のようなサービスクラスが定義されていたとする。

    アプリ名ディレクトリ/app/Services/TestService.php
    <?php
    
    namespace App\Services;
    
    class TestService
    {
        /**
         * 定義された文字列を返す
         *
         * @return string
         */
        public function returnStr()
        {
            return 'これはTestServiceクラスのreturnStr()メソッドで定義された文字列です';
        }
    }
    
  • 上記のTestServiceクラスのreturnStr()メソッドをbladeファイルで呼び出したい時、下記のように記載する。

    foo.blade.php
    @inject('testService', 'App\Services\TestService')
    {{ $testService->returnStr() }}
    
  • ローカルサーバーを起動し、当該のbladeファイルがビューとしてリンクしているURLへアクセスすると下記のように表示される。

    Document.png

参考文献

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?