20210726のlaravelに関する記事は8件です。

プログラミング初心者が書いたバリデーションを日本語に変える方法

はじめに Laravelにてフォームを作成した際に、必ずといっていいほどバリデーションを実装すると思います。 最初の段階では英語の状態になっていて、個人的には日本語がいいなぁと思い色々と調べてみた結果 割と簡単に日本語のエラーメッセージに直せることが分かったのでメモとして残します。 日本語バリデーションの実装 現在Laravel青本を読みながらフォームを作っておりまして、現在の段階はこんな感じです。 なんだか英語ばっかりで嫌になっちゃいますね。。。 というわけで日本語に早速変えていきます。 まずは/config/app.phpの中を変えていきます。 app.php |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', ここの'locale' => 'en',を'locale' => 'ja',に変更します。 次にlangフォルダの中にenという初期から入っているフォルダがあるので それを丸々コピーして同様にlangフォルダの直下に置いておきます。 そしてjaの中のvalidation.phpのコードを全て下記のものに変えます。 validation.php <?php return [ /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used by | the validator class. Some of these rules have multiple versions such | as the size rules. Feel free to tweak each of these messages here. | */ 'accepted' => ':attributeを承認してください。', 'active_url' => ':attributeは、有効なURLではありません。', 'after' => ':attributeには、:dateより後の日付を指定してください。', 'after_or_equal' => ':attributeには、:date以降の日付を指定してください。', 'alpha' => ':attributeには、アルファベッドのみ使用できます。', 'alpha_dash' => ":attributeには、英数字('A-Z','a-z','0-9')とハイフンと下線('-','_')が使用できます。", 'alpha_num' => ":attributeには、英数字('A-Z','a-z','0-9')が使用できます。", 'array' => ':attributeには、配列を指定してください。', 'before' => ':attributeには、:dateより前の日付を指定してください。', 'before_or_equal' => ':attributeには、:date以前の日付を指定してください。', 'between' => [ 'numeric' => ':attributeには、:minから、:maxまでの数字を指定してください。', 'file' => ':attributeには、:min KBから:max KBまでのサイズのファイルを指定してください。', 'string' => ':attributeは、:min文字から:max文字にしてください。', 'array' => ':attributeの項目は、:min個から:max個にしてください。', ], 'boolean' => ":attributeには、'true'か'false'を指定してください。", 'confirmed' => ':attributeと:attribute確認が一致しません。', 'date' => ':attributeは、正しい日付ではありません。', 'date_equals' => ':attributeは:dateに等しい日付でなければなりません。', 'date_format' => ":attributeの形式は、':format'と合いません。", 'different' => ':attributeと:otherには、異なるものを指定してください。', 'digits' => ':attributeは、:digits桁にしてください。', 'digits_between' => ':attributeは、:min桁から:max桁にしてください。', 'dimensions' => ':attributeの画像サイズが無効です', 'distinct' => ':attributeの値が重複しています。', 'email' => ':attributeは、有効なメールアドレス形式で指定してください。', 'ends_with' => 'The :attribute must end with one of the following: :values', 'exists' => '選択された:attributeは、有効ではありません。', 'file' => ':attributeはファイルでなければいけません。', 'filled' => ':attributeは必須です。', 'gt' => [ 'numeric' => ':attributeは、:valueより大きくなければなりません。', 'file' => ':attributeは、:value KBより大きくなければなりません。', 'string' => ':attributeは、:value文字より大きくなければなりません。', 'array' => ':attributeの項目数は、:value個より大きくなければなりません。', ], 'gte' => [ 'numeric' => ':attributeは、:value以上でなければなりません。', 'file' => ':attributeは、:value KB以上でなければなりません。', 'string' => ':attributeは、:value文字以上でなければなりません。', 'array' => ':attributeの項目数は、:value個以上でなければなりません。', ], 'image' => ':attributeには、画像を指定してください。', 'in' => '選択された:attributeは、有効ではありません。', 'in_array' => ':attributeが:otherに存在しません。', 'integer' => ':attributeには、整数を指定してください。', 'ip' => ':attributeには、有効なIPアドレスを指定してください。', 'ipv4' => ':attributeはIPv4アドレスを指定してください。', 'ipv6' => ':attributeはIPv6アドレスを指定してください。', 'json' => ':attributeには、有効なJSON文字列を指定してください。', 'lt' => [ 'numeric' => ':attributeは、:valueより小さくなければなりません。', 'file' => ':attributeは、:value KBより小さくなければなりません。', 'string' => ':attributeは、:value文字より小さくなければなりません。', 'array' => ':attributeの項目数は、:value個より小さくなければなりません。', ], 'lte' => [ 'numeric' => ':attributeは、:value以下でなければなりません。', 'file' => ':attributeは、:value KB以下でなければなりません。', 'string' => ':attributeは、:value文字以下でなければなりません。', 'array' => ':attributeの項目数は、:value個以下でなければなりません。', ], 'max' => [ 'numeric' => ':attributeには、:max以下の数字を指定してください。', 'file' => ':attributeには、:max KB以下のファイルを指定してください。', 'string' => ':attributeは、:max文字以下にしてください。', 'array' => ':attributeの項目は、:max個以下にしてください。', ], 'mimes' => ':attributeには、:valuesタイプのファイルを指定してください。', 'mimetypes' => ':attributeには、:valuesタイプのファイルを指定してください。', 'min' => [ 'numeric' => ':attributeには、:min以上の数字を指定してください。', 'file' => ':attributeには、:min KB以上のファイルを指定してください。', 'string' => ':attributeは、:min文字以上にしてください。', 'array' => ':attributeの項目は、:min個以上にしてください。', ], 'not_in' => '選択された:attributeは、有効ではありません。', 'not_regex' => ':attributeの形式が無効です。', 'numeric' => ':attributeには、数字を指定してください。', 'password' => ':attributeが間違っています', 'present' => ':attributeが存在している必要があります。', 'regex' => ':attributeには、有効な正規表現を指定してください。', 'required' => ':attributeは、必ず指定してください。', 'required_if' => ':otherが:valueの場合、:attributeを指定してください。', 'required_unless' => ':otherが:values以外の場合、:attributeを指定してください。', 'required_with' => ':valuesが指定されている場合、:attributeも指定してください。', 'required_with_all' => ':valuesが全て指定されている場合、:attributeも指定してください。', 'required_without' => ':valuesが指定されていない場合、:attributeを指定してください。', 'required_without_all' => ':valuesが全て指定されていない場合、:attributeを指定してください。', 'same' => ':attributeと:otherが一致しません。', 'size' => [ 'numeric' => ':attributeには、:sizeを指定してください。', 'file' => ':attributeには、:size KBのファイルを指定してください。', 'string' => ':attributeは、:size文字にしてください。', 'array' => ':attributeの項目は、:size個にしてください。', ], 'starts_with' => ':attributeは、次のいずれかで始まる必要があります。:values', 'string' => ':attributeには、文字を指定してください。', 'timezone' => ':attributeには、有効なタイムゾーンを指定してください。', 'unique' => '指定の:attributeは既に使用されています。', 'uploaded' => ':attributeのアップロードに失敗しました。', 'url' => ':attributeは、有効なURL形式で指定してください。', 'uuid' => ':attributeは、有効なUUIDでなければなりません。', /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute.rule" to name the lines. This makes it quick to | specify a specific custom language line for a given attribute rule. | */ 'custom' => [ 'attribute-name' => [ 'rule-name' => 'custom-message', ], ], /* |-------------------------------------------------------------------------- | Custom Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap our attribute placeholder | with something more reader friendly such as "E-Mail Address" instead | of "email". This simply helps us make our message more expressive. | */ 'attributes' => [], ]; これに関しては丸々コピペで大丈夫です。 そして再びフォームの方で実行してみると。。。。 という風に日本語に変わりましたね! これにてバリデーションの変更は完了です。 何か誤っている点などがありましたらご指摘お願いします! 参考資料 https://qiita.com/ama_keshi/items/27292949d41fdd8bd930 https://s-yqual.com/blog/914
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

AWS Cloud9 でAmazon Linux 2でLaravelの設定

Amazon Linux2 ではEPELが使えない EPELが何かは知りません。調べたら追記します! とりあえず仕様している教材に amazon linuxを使ってください。linux 2ではEPELが使えないので。 みたいに書いてあったけど、 AWSのCloud9でワークスペースを作成する際に、 Amazon Linux 2 (recommended) と合ったので、せっかくなら推奨版が使いたいなということで、環境を少しアレンジ。 まああとは自分で調べてEPELが使えればいいだろうという考え。というか推奨版なんだから当然使えるっしょ!の乗りです。 手動でEPELを有効にする この通りにやれば大丈夫っぽい。 sudo amazon-linux-extras install epel -y phpのバージョン確認 $ php -v PHP 7.2.24 (cli) (built: Oct 31 2019 18:27:08) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies 2021/07/26の段階では7.2.24が標準でインストールされるらしい。 amazon linuxの方だと5系になるのかな?? composeのインストール $ curl -sS https://getcomposer.org/installer | php All settings correct for using Composer Downloading... Composer (version 2.1.5) successfully installed to: /home/ec2-user/environment/composer.phar Use it: php composer.phar # このままだとcomposerのパスが通ってない? $ composer bash: composer: command not found # composer.pharを移動してパスを通す $ sudo mv composer.phar /usr/local/bin/composer # 再確認 $ composer ______ / ____/___ ____ ___ ____ ____ ________ _____ / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/ / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ / \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/ /_/ Composer version 2.1.5 2021-07-23 10:35:47 Usage: command [options] [arguments] Options: -h, --help Display this help message -q, --quiet Do not output any message -V, --version Display this application version --ansi Force ANSI output --no-ansi Disable ANSI output -n, --no-interaction Do not ask any interactive question --profile Display timing and memory usage information --no-plugins Whether to disable plugins. -d, --working-dir=WORKING-DIR If specified, use the given directory as working directory. --no-cache Prevent use of the cache -v|vv|vvv, --verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug Available commands: about Shows a short information about Composer. archive Creates an archive of this composer package. browse Opens the package's repository URL or homepage in your browser. cc Clears composer's internal package cache. check-platform-reqs Check that platform requirements are satisfied. clear-cache Clears composer's internal package cache. clearcache Clears composer's internal package cache. config Sets config options. create-project Creates new project from a package into given directory. depends Shows which packages cause the given package to be installed. diagnose Diagnoses the system to identify common errors. dump-autoload Dumps the autoloader. dumpautoload Dumps the autoloader. exec Executes a vendored binary/script. fund Discover how to help fund the maintenance of your dependencies. global Allows running commands in the global composer dir ($COMPOSER_HOME). help Displays help for a command home Opens the package's repository URL or homepage in your browser. i Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json. info Shows information about packages. init Creates a basic composer.json file in current directory. install Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json. licenses Shows information about licenses of dependencies. list Lists commands outdated Shows a list of installed packages that have updates available, including their latest version. prohibits Shows which packages prevent the given package from being installed. reinstall Uninstalls and reinstalls the given package names remove Removes a package from the require or require-dev. require Adds required packages to your composer.json and installs them. run Runs the scripts defined in composer.json. run-script Runs the scripts defined in composer.json. search Searches for packages. self-update Updates composer.phar to the latest version. selfupdate Updates composer.phar to the latest version. show Shows information about packages. status Shows a list of locally modified packages. suggests Shows package suggestions. u Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file. update Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file. upgrade Upgrades your dependencies to the latest version according to composer.json, and updates the composer.lock file. validate Validates a composer.json and composer.lock. why Shows which packages cause the given package to be installed. why-not Shows which packages prevent the given package from being installed. いけた! Laravelプロジェクトを作成 $ composer create-project laravel/laravel ./laravel-quest "5.5.*" --prefer-distCreating a "laravel/laravel" project at "./laravel-quest" Installing laravel/laravel (v5.5.28) - Downloading laravel/laravel (v5.5.28) - Installing laravel/laravel (v5.5.28): Extracting archive Created project in /home/ec2-user/environment/./laravel-quest > @php -r "file_exists('.env') || copy('.env.example', '.env');" Loading composer repositories with package information Updating dependencies Your requirements could not be resolved to an installable set of packages. Problem 1 - laravel/framework[v5.5.0, ..., v5.5.50] require ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension. - Root composer.json requires laravel/framework 5.5.* -> satisfiable by laravel/framework[v5.5.0, ..., v5.5.50]. - なんか問題が発生している。。。 laravel/framework[v5.5.0, ..., v5.5.50] require ext-mbstring * -> it is missing from your system. Install or enable PHP's mbstring extension. extensionが無い、もしくは有効になっていないということですね。 ちなみにこの状態でもLaravelプロジェクトは作成されています。 しかし起動しようとするとできません。 $ php artisan serve --port=80 PHP Warning: require(/home/ec2-user/environment/laravel-quest/vendor/autoload.php): failed to open stream: No such file or directory in /home/ec2-user/environment/laravel-quest/artisan on line 18 PHP Fatal error: require(): Failed opening required '/home/ec2-user/environment/laravel-quest/vendor/autoload.php' (include_path='.:/usr/share/pear:/usr/share/php') in /home/ec2-user/environment/laravel-quest/artisan on line 18 autoload.phpがないって言われてるんですね。 よくわかりませんが、serverが入ってないから起動できないということだと思います。 なので手動で入れる。 WebサーバApacheはamazon-linux-extrasにないらしい ここのとおりにやれば大丈夫でした。 # aparchのインストール $ sudo yum install -y httpd Loaded plugins: extras_suggestions, langpacks, priorities, update-motd amzn2-core | 3.7 kB 00:00:00 242 packages excluded due to repository priority protections Package httpd-2.4.48-2.amzn2.x86_64 already installed and latest version Nothing to do # 入ってるやん! # サーバの確認 $ httpd -v Server version: Apache/2.4.48 () // 入ってます! Server built: Jun 25 2021 18:53:37 # php関連のインストール $ sudo yum install php php-mbstring php-pdo php-gd php-xml Loaded plugins: extras_suggestions, langpacks, priorities, update-motd 242 packages excluded due to repository priority protections Package php-pdo-7.2.24-1.amzn2.0.1.x86_64 already installed and latest version Package php-xml-7.2.24-1.amzn2.0.1.x86_64 already installed and latest version Resolving Dependencies --> Running transaction check ---> Package php.x86_64 0:7.2.24-1.amzn2.0.1 will be installed ---> Package php-gd.x86_64 0:7.2.24-1.amzn2.0.1 will be installed --> Processing Dependency: libXpm.so.4()(64bit) for package: php-gd-7.2.24-1.amzn2.0.1.x86_64 --> Processing Dependency: libX11.so.6()(64bit) for package: php-gd-7.2.24-1.amzn2.0.1.x86_64 ---> Package php-mbstring.x86_64 0:7.2.24-1.amzn2.0.1 will be installed --> Processing Dependency: libonig.so.2()(64bit) for package: php-mbstring-7.2.24-1.amzn2.0.1.x86_64 --> Running transaction check ---> Package libX11.x86_64 0:1.6.7-3.amzn2.0.2 will be installed --> Processing Dependency: libX11-common >= 1.6.7-3.amzn2.0.2 for package: libX11-1.6.7-3.amzn2.0.2.x86_64 --> Processing Dependency: libxcb.so.1()(64bit) for package: libX11-1.6.7-3.amzn2.0.2.x86_64 ---> Package libXpm.x86_64 0:3.5.12-1.amzn2.0.2 will be installed ---> Package oniguruma.x86_64 0:5.9.6-1.amzn2.0.4 will be installed --> Running transaction check ---> Package libX11-common.noarch 0:1.6.7-3.amzn2.0.2 will be installed ---> Package libxcb.x86_64 0:1.12-1.amzn2.0.2 will be installed --> Processing Dependency: libXau.so.6()(64bit) for package: libxcb-1.12-1.amzn2.0.2.x86_64 --> Running transaction check ---> Package libXau.x86_64 0:1.0.8-2.1.amzn2.0.2 will be installed --> Finished Dependency Resolution Dependencies Resolved ====================================================================================================== Package Arch Version Repository Size ====================================================================================================== Installing: php x86_64 7.2.24-1.amzn2.0.1 amzn2extra-lamp-mariadb10.2-php7.2 2.9 M php-gd x86_64 7.2.24-1.amzn2.0.1 amzn2extra-lamp-mariadb10.2-php7.2 179 k php-mbstring x86_64 7.2.24-1.amzn2.0.1 amzn2extra-lamp-mariadb10.2-php7.2 501 k Installing for dependencies: libX11 x86_64 1.6.7-3.amzn2.0.2 amzn2-core 606 k libX11-common noarch 1.6.7-3.amzn2.0.2 amzn2-core 165 k libXau x86_64 1.0.8-2.1.amzn2.0.2 amzn2-core 29 k libXpm x86_64 3.5.12-1.amzn2.0.2 amzn2-core 57 k libxcb x86_64 1.12-1.amzn2.0.2 amzn2-core 216 k oniguruma x86_64 5.9.6-1.amzn2.0.4 amzn2-core 127 k Transaction Summary ====================================================================================================== Install 3 Packages (+6 Dependent packages) Total download size: 4.7 M Installed size: 16 M Is this ok [y/d/N]: y Downloading packages: (1/9): libX11-common-1.6.7-3.amzn2.0.2.noarch.rpm | 165 kB 00:00:00 (2/9): libXau-1.0.8-2.1.amzn2.0.2.x86_64.rpm | 29 kB 00:00:00 (3/9): libXpm-3.5.12-1.amzn2.0.2.x86_64.rpm | 57 kB 00:00:00 (4/9): libX11-1.6.7-3.amzn2.0.2.x86_64.rpm | 606 kB 00:00:00 (5/9): oniguruma-5.9.6-1.amzn2.0.4.x86_64.rpm | 127 kB 00:00:00 (6/9): libxcb-1.12-1.amzn2.0.2.x86_64.rpm | 216 kB 00:00:00 (7/9): php-gd-7.2.24-1.amzn2.0.1.x86_64.rpm | 179 kB 00:00:00 (8/9): php-7.2.24-1.amzn2.0.1.x86_64.rpm | 2.9 MB 00:00:00 (9/9): php-mbstring-7.2.24-1.amzn2.0.1.x86_64.rpm | 501 kB 00:00:00 ------------------------------------------------------------------------------------------------------ Total 10 MB/s | 4.7 MB 00:00:00 Running transaction check Running transaction test Transaction test succeeded Running transaction Installing : oniguruma-5.9.6-1.amzn2.0.4.x86_64 1/9 Installing : libXau-1.0.8-2.1.amzn2.0.2.x86_64 2/9 Installing : libxcb-1.12-1.amzn2.0.2.x86_64 3/9 Installing : libX11-common-1.6.7-3.amzn2.0.2.noarch 4/9 Installing : libX11-1.6.7-3.amzn2.0.2.x86_64 5/9 Installing : libXpm-3.5.12-1.amzn2.0.2.x86_64 6/9 Installing : php-gd-7.2.24-1.amzn2.0.1.x86_64 7/9 Installing : php-mbstring-7.2.24-1.amzn2.0.1.x86_64 8/9 Installing : php-7.2.24-1.amzn2.0.1.x86_64 9/9 Verifying : libX11-1.6.7-3.amzn2.0.2.x86_64 1/9 Verifying : php-mbstring-7.2.24-1.amzn2.0.1.x86_64 2/9 Verifying : libxcb-1.12-1.amzn2.0.2.x86_64 3/9 Verifying : libX11-common-1.6.7-3.amzn2.0.2.noarch 4/9 Verifying : php-7.2.24-1.amzn2.0.1.x86_64 5/9 Verifying : libXpm-3.5.12-1.amzn2.0.2.x86_64 6/9 Verifying : libXau-1.0.8-2.1.amzn2.0.2.x86_64 7/9 Verifying : php-gd-7.2.24-1.amzn2.0.1.x86_64 8/9 Verifying : oniguruma-5.9.6-1.amzn2.0.4.x86_64 9/9 Installed: php.x86_64 0:7.2.24-1.amzn2.0.1 php-gd.x86_64 0:7.2.24-1.amzn2.0.1 php-mbstring.x86_64 0:7.2.24-1.amzn2.0.1 Dependency Installed: libX11.x86_64 0:1.6.7-3.amzn2.0.2 libX11-common.noarch 0:1.6.7-3.amzn2.0.2 libXau.x86_64 0:1.0.8-2.1.amzn2.0.2 libXpm.x86_64 0:3.5.12-1.amzn2.0.2 libxcb.x86_64 0:1.12-1.amzn2.0.2 oniguruma.x86_64 0:5.9.6-1.amzn2.0.4 Complete! # 以下を実行してautoload.phpを作成する $ composer install # 以下でサーバが起動できます。。。が!ブラウザは開けません! $ php artisan serve --port=8080 No application encryption key has been specified.が発生してブラウザが開けない https://qiita.com/ponsuke0531/items/197c76fcb9300d7c5f36 ここのとおりにやったら大丈夫です。 $ cat .env | grep ^APP_ APP_NAME=Laravel APP_ENV=local APP_KEY= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost # 以下を実行するとAPP_KEYに自動的に追記される $ php artisan key:generate $ cat .env | grep ^APP_ APP_NAME=Laravel APP_ENV=local APP_KEY=base64:dvObQrZ9xEdYJaaaaaaaaaa/uFU3ADAsKtxxxxxxxxx= APP_DEBUG=true APP_LOG_LEVEL=debug APP_URL=http://localhost # 設定ファイルのキャッシュを再作成する $ php artisan config:cache Configuration cache cleared! Configuration cached successfully! これでブラウザが起動できるはず! やっとスタートラインです!頑張りましょう!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel6.x系cloud9使っての開発

SQLSTATE[HY000] [1049] Unknown database 'laravel'と出た時の解消法 php artisan cache:clear を実行し、サーバーを再起動したら治りました。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelのクエリビルダで使われる比較演算子について

Laravelのクエリビルダで下記のようなコードを見つけた。 ->where('team_id', '<>', $team_id) あまり見慣れなかった比較演算子だったので再度調べた所、 「 a <> b 」  は 「 a と b は等しくない 」 という意味らしい。 つまり、下記は「team_idと$team_idが等しくないもの」という条件指定となる。 ->where('team_id', '<>', $team_id) 「<、<=」などは条件分岐で馴染みがあるが、 SQL独自の比較演算子なのか「<>、a <=> b」などは知らなかったので今後のために覚えておく。 参考記事はこちら↓
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelは複数のwhereを配列で一括指定できる

Laravelのクエリビルダでwhereで複数条件指定する際は ->where('id', $id)->where('name', $name) とするのもアリだが、複数指定は下記ように配列で指定するほうが可読性が上がる。 ->where([ ['id', '=', $id], ['name', '=', $name], ]) 【おまけ】Eloquentとクエリビルダの違いの再確認 下記記事がわかりやすかった。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel用パッケージでArtisanコマンドを書く場合のテスト

発生事象 Laravel用のパッケージを書いていて、コマンドを追加したのでテストしてみるぞ~、と思ったら、以下のようなエラーメッセージが出た。 sampleTest.php //テストはだいたいこんな感じ class SampleTest extends \Orchestra\Testbench\TestCase { public function test_command(){ $this->artisan('nice:easy')->assertExitCode(10); } } Symfony\Component\Console\Exception\CommandNotFoundException: The command "nice:easy" does not exist. コマンドを認識していないようだ。 結論 ココを見ましょう。 https://orchestraplatform.readme.io/docs/testbench#section-custom-service-providers https://orchestraplatform.readme.io/docs/testbench To load your package service provider, override the getPackageProviders() おまえのパッケージのサービスプロバイダをロードするには、getPackageProviders() をオーバーライドせい、ということで、解決。 補足 コマンド登録はパッケージのサービスプロバイダに書く Artisanコマンドを提供するようなLaravel用パッケージを作成する場合、パッケージ側にサービスプロバイダを用意して、「この辺のクラスをArtisanコマンドに追加せよ」という情報を、利用側のLaravel本体に知らせる必要があります。 =>このへんの話 https://laravel.com/docs/8.x/packages#commands https://readouble.com/laravel/8.x/ja/packages.html#commands パッケージ開発のテストには orchestral/testbench を使う Laravel用パッケージを開発する場合、Testには https://github.com/orchestral/testbench を使いましょう。 =>このへんの話 https://readouble.com/laravel/8.x/ja/packages.html#a-note-on-facades FeatureTestですよ、という話 そもそもの話として、Artisanコマンド(Illuminate\Console\Command を継承したクラス)に対してUnitTestを書こうとすると、色々と面倒なことになる(何が面倒なのか書くのもめんどい)。 Artisanコマンドを書く場合は、責任の範囲を画面との入出力のみに限定し、それ以外の処理に関しては適切に移譲するように注意しする。 端的には、Illuminate\Console\Command を継承して作成するクラスは、ViewとControllerに相当するもの、と扱っておけばよい。(なので、Artisanコマンドに対するテストは、UnitTestでははなくFeatureTestです。) Commandのコンストラクタをオーバライドするなよ、という話 ちなみに、Illuminate\Console\Command を継承してクラスを作成する場合は コンストラクタをオーバーライドしてはいけない。 理由はこちら https://qiita.com/k-kurikuri/items/cec750ec3d21c6319253 移譲先のオブジェクト生成は、handle()メソッドの先頭で行うようにしておくのが良いと思う。 SampleCommand.php class TemplateList extends Command { /** @var string $signature */ protected $signature = 'big-na-otoko:do-it'; /** @var string $description */ protected $description = '将来なにかデカイことをやるコマンドです'; /** @var NiceService $service */ private $service; /** * @return void */ public function handle() { try { $this->init(); } catch (\Throwable $e) { $this->error($e->getMessage()); return 1; } //以下に、入出力に関する処理とサービスの呼び出しなどを書いて適宜実装していく } /** * @return void */ private function init(): void { $this->service = App::make(NiceService ::class); } } こんなノリで書いておけば、だいたい問題なくテストできるはず。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

composer のコマンドを勉強してみた

composer は Laravel インストールする時に使った事はあるけれど、特に意識することなく(何も考えずに)使ってました・・・ そんな中、Laravel の carbon パッケージを調べる事があり、ふと「このcarbonってバージョンいくつなんだろう」と疑問に思った事が composer のコマンド使ってみたきっかけです。 備忘録的な意味合いが強いのですが、誰か、何かの役に立てばうれしいです。 パッケージの一覧を表示する composer show -i You are using the deprecated option "installed". Only installed packages are shown by default now. The --all option can be used to show all packages. ~~~ 略 ~~~ monolog/monolog 2.2.0 Sends your logs to files, sockets, inboxes, databases and various web services nesbot/carbon 2.46.0 An API extension for DateTime that supports 281 different languages. ~~~ 略 ~~~ いろいろと出力されました。carbon のバージョンは 2.46.0 のようです。 composer update と composer install よくcomposer updateは本番環境では実行しない事!なんてことを聞きますが何でですかね?あまり知らなかったのですが、今回調べた事を記します。 まずはcomposer updateとcomposer installの対比表 実行コマンド 対 composer.json 対 composer.lock composer install 参照のみ 参照のみ composer update 参照のみ 書き込みあり     composer install の動き 1. composer.lock が存在すればファイル内に記されたパッケージのバージョン情報を取得する 2. composer.json ファイル内に記載されたパッケージをcomposer.lockに記されたバージョン情報に従ってパッケージのダウンロード・インストールを行う composer.lockとcomposer.jsonは読み込みのみ     composer update の動き 1. composer.json ファイル内に記載されたパッケージとバージョン情報に従ってダウンロード・インストールを行う 2. インストールしたパッケージ情報でcomposer.lock を更新する composer.lockは書き込み     composer.lockはチーム内などで共有し、必要のないパッケージのバージョンアップを行わない為に使用されます。これを使用する事で意図しないバージョンアップによる不具合、コンフリクトを防ぎます。 そのcomposer.lockをcomposer updateでは更新します。 なので、通常の流れでは 開発環境でcomposer updateを実行 composer.lock composer.jsonファイルを共有 本番環境で共有したcomposer.lockを使用してcomposer installを実行 という事になるのかな?? 実際に本番環境でcomposer updateを行って、意図しないバージョンまでアップデートされ、その結果、稼働してたシステムが動かなくなったというケースを見たことがあります。       とりあえずこんなところで 勉強中なので必要があれば、追記、修正していきます。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel、プロキシサーバーの対応【個人用メモ】

本番環境での原因特定に苦労したので、 次同じ状況ですぐに反応できようように。 [url]https://readouble.com/laravel/6.x/ja/requests.html
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む