0
0

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 1 year has passed since last update.

Laravelで共通関数作成

Last updated at Posted at 2023-04-22

Laravelで共通関数作成、個人メモ。

環境

  • Laravel 10.4.1
  • PHP 8.2.4

作業

  • \app\Libs

    Common.php
    を作成。(フォルダ名、ファイル名は任意)
    下記では例として、「get_img_path」関数を作成。
Common.php
<?php
namespace App\Libs;
class Common
{
    //ユーザーの画像パスを返す
    public static function get_img_path($db_img){

        if($db_img == 'noimage.jpg'){
            $img = '/storage/default/noimage.jpg';
        }else{
            $img = '/storage/todo/' .  $db_img;
        }        
        return $img;

    }   //end funtion index
}
  • \config\app.php 最下部に下記追加
app.php
()
    /*
    |--------------------------------------------------------------------------
    | Class Aliases
    |--------------------------------------------------------------------------
    |
    | This array of class aliases will be registered when this application
    | is started. However, feel free to register as many as you wish as
    | the aliases are "lazy" loaded so they don't hinder performance.
    |
    */

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

    'aliases' => Facade::defaultAliases()->merge([
        'Common' => App\Libs\Common::class, 
    ])->toArray(),

※エイリアスの説明部分の日本語訳は
このクラス エイリアスの配列は、このアプリケーションの起動時に登録されます。 ただし、エイリアスは「遅延」ロードされるため、パフォーマンスを妨げないため、好きなだけ登録してください。

  • コントローラーファイル内で共通関数を使用。上部にuse宣言は不要。この例では \Common::get_img_path() で呼び出せる。
$img = \Common::get_img_path($user->img);  //共通関数で画像パス取得

参考

Laravel 共通関数作成

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?