20190811のlaravelに関する記事は4件です。

Laravelにサービス層を導入する

はじめに

LaravelでWebサービスを開発していると、最初はいいのですが、Controillerが大量のロジックで埋め尽くされ見通しが悪くなっていきます。
それを改善する為にサービス層を導入します。

1.サービスクラスの作成

今回はappの直下にServiceディレクトリを作成し、PostServiceクラスを作成します。
例としてechohogeメソッドを作成します。

PostService.php
<?php
namespace App\Service;

use Illuminate\Support\Facades\DB;

class PostService
{
    public function echoHoge()
    {
        return 'hoge';
    } 
}

2.サービスコンテナへ登録する

まずはLaravelのartisanコマンドを使用し、サービスプロバイダを作成します。

php artisan make:provider PostServiceProvider
PostserviceProvider.php
<?php

namespace App\Providers;

use App\Service\PostService;
use Illuminate\Support\ServiceProvider;

class PostServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('Post',function($app){
            return new PostService();
        });
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

3.オートロード設定を行う

app.php
'providers' => [
    /*
   省略
    */
        App\Providers\PostServiceProvider::class,
    ],

4.依存性注入を行う

最後にコントローラーのコンストラクタで注入していきます。

PostController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Service\PostService;
use App\Post;

class PostController extends Controller
{

    protected $postservice;

    //投稿系のサービス層をDIする
    public function __construct(PostService $postservice)
    {
        $this->postservice = $postservice;
    }

    //一覧表示
    public function index()
    {
        //サービス層のメソッドを使用する
        return $this->postservice->echoHoge();
    }
}

以上です!!
これでサービス層としてビジネスロジックを書ける場所ができました!

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel5.8でランダム文字列を生成するStr::random()

phpstormでlaravel5.8内でstr_random()を使ったらstr_random()みたいになったので、新しいメソッドを探した。

5.8系では、str_random()は、非推奨みたい。

use Illuminate\Support\Str;

$random_str = Str::random(100);

ちなみに5.8でstr_random()を呼ぶと内部でStr::random()が呼ばれるみたい。

vendor/laravel/framework/src/Illuminate/Support/helpers.phpより
if (! function_exists('str_random')) {
    /**
     * Generate a more truly "random" alpha-numeric string.
     *
     * @param  int  $length
     * @return string
     *
     * @throws \RuntimeException
     *
     * @deprecated Str::random() should be used directly instead. Will be removed in Laravel 6.0.
     */
    function str_random($length = 16)
    {
        return Str::random($length);
    }
}

Laravel 5.8 New Features List
*) Deprecated String and Array Helpers Functions

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel 認証で$requestは合っているのに認証されなかった理由

Laravel5.7の認証で$requestの値は合っているのにLoginができなかった理由

マルチ認証でAdminのデータをseederファイルに書いてDBに入れた。

その時に'password' => 'passwordとそのままにしていたので値は合っているのにloginができなかった。

'password' => Hash::make('password')
Hash化しないといけないようでした:dancers:
もし同じように悩んでる人の手伝いになればウレシスです:relaxed:

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class BrandsTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('brands')->insert([
            [
                'created_at' => date('Y-m-d H:i:s'),
                'brand_name' => 'Apuweiser-riche',
                'brand_name_kana' =>'アプワイザーリッシェ' ,
                'category' => 'feminine',
                'password' => Hash::make('password'),
            ],
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

How to deploy and migrate Laravel-Admin on ECS

I made a management screen using Laravel-Admin.
However, I was a little confused when deploy and migrate to an environment build by ECS.

At local environment

You can easy to run Laravel-Admin on local environment just as written on document.
However, it's a bit different for environment made by ECS.

Answer

To conclude, run composer install and vendor:publish on the Docker file when building.
After that, you can migrate admin and application tables with ecs-cli command.

Deploy

Dockefile
...
RUN composer install \      
    && php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider"
...

Then, deploy to production environment.

Migration

After deploying, you use "ecs-cli compose start" command which can execute command like a "heroku run".
ecs-cli compose start

docker-composer.migration.yml
version: '2'                                  
services:                                     
  app:                                        
    command: bash -c "php artisan migrate:refresh --seed && echo 'yes' | php artisan admin:install"

This is actual command we use to migrate.

$ ecs-cli compose \
    --cluster-config app-dev \
    --project-name app-migration-ecs-cli \
    --file docker-compose.development.yml \
    --file docker-compose.migration.yml \
    --ecs-params ecs/ecs-params.development.yml \
        start

Issues I faced

Laravel confirms migration for production environment.

Package manifest generated successfully.
Copied Directory [/vendor/encore/laravel-admin/config] To [/config]
Copied Directory [/vendor/encore/laravel-admin/resources/lang] To [/resources/lang]
Copied Directory [/vendor/encore/laravel-admin/database/migrations] To [/database/migrations]
Copied Directory [/vendor/encore/laravel-admin/resources/assets] To [/public/vendor/laravel-admin]
Publishing complete.
**************************************
*     Application In Production!     *
**************************************

 Do you really wish to run this command? (yes/no) [no]:
 > 

  Aborted.  

Docker file at that time is here.

Dockerfile
...
RUN composer install \  
    && php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider" \
    && php artisan admin:install
...

Detail

vendor/laravel/framework/src/Illuminate/Database/Console/Migrations/MigrateCommand.php
class MigrateCommand extends BaseCommand {

    use ConfirmableTrait;
vendor/laravel/framework/src/Illuminate/Console/ConfirmableTrait.php
trait ConfirmableTrait {
    //...
    public function confirmToProceed($warning = 'Application In Production!', Closure $callback = null)
    {
        $shouldConfirm = $callback ?: $this->getDefaultConfirmCallback();

        if (call_user_func($shouldConfirm))
        {
            if ($this->option('force')) return true;
            //...
        }
    //...
    }
    //...
    protected function getDefaultConfirmCallback()
    {
        return function() { return $this->getLaravel()->environment() == 'production'; };
    }

Solution

I tried to add "--force" option to command.

php artisan admin:install doesn't have force option.

Package manifest generated successfully.
Copied Directory [/vendor/encore/laravel-admin/config] To [/config]
Copied Directory [/vendor/encore/laravel-admin/resources/lang] To [/resources/lang]
Copied Directory [/vendor/encore/laravel-admin/database/migrations] To [/database/migrations]
Copied Directory [/vendor/encore/laravel-admin/resources/assets] To [/public/vendor/laravel-admin]
Publishing complete.

[2019-08-08 19:53:33] production.ERROR: The "--force" option does not exist. {"exception":"[object] (Symfony\\Component\\Console\\Exception\\RuntimeException(code: 0): The \"--force\" option does not exist. at /var/www/html/vendor/symfony/console/Input/ArgvInput.php:218)

Oops.

Docker file at that time is here.

Dockerfile
...
RUN composer install \  
    && php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider" \
    && php artisan admin:install --force
...

Solution

I tried to say yes using standard output when Laravel confirms.

We can't connect to DB yet when building.

Package manifest generated successfully.
Copied Directory [/vendor/encore/laravel-admin/config] To [/config]
Copied Directory [/vendor/encore/laravel-admin/resources/lang] To [/resources/lang]
Copied Directory [/vendor/encore/laravel-admin/database/migrations] To [/database/migrations]
Copied Directory [/vendor/encore/laravel-admin/resources/assets] To [/public/vendor/laravel-admin]
Publishing complete.
**************************************
*     Application In Production!     *
**************************************

 Do you really wish to run this command? (yes/no) [no]:
 > 
[2019-08-08 20:28:00] production.ERROR: SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = forge and table_name = migrations and table_type = 'BASE TABLE') {"exception":"[object] (Illuminate\\Database\\QueryException(code: 2002): SQLSTATE[HY000] [2002] Connection refused (SQL: select * from information_schema.tables where table_schema = forge and table_name = migrations and table_type = 'BASE TABLE') at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\\DBAL\\Driver\\PDOException(code: 2002): SQLSTATE[HY000] [2002] Connection refused at /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:3

Docker file at that time is here.

Dockerfile
...
RUN composer install \  
    && php artisan vendor:publish --provider="Encore\Admin\AdminServiceProvider" \
    && echo "yes" | php artisan admin:install
...

Solution

I tried to separate timing of execution command building and migration.

  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む