Laravel Backpackを使ってみた! - カスタマイズ編2

こんにちは、コバヤシです。
引き続きLaravel Backpackをカスタマイズしていきます。

前回まではこちら。

tech.arms-soft.co.jp

tech.arms-soft.co.jp

バリデーションを実装する

まずはバリデーションを設定したいと思います。
今回はForm Requestでバリデーションを設定します。

インストール編でも書きましたが、

php artisan backpack:crud

のコマンドでコントローラー等を作成した時に、 バリデーションを書く場所を「request」にしていると app/Http/Requests/以下にファイルが出力されているはずです。

laravel/app/Http/Requests/UserRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        // only allow updates if the user is logged in
        return backpack_auth()->check();
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rule = [
            'name' => ['required', 'max:50'],
            'email' => ['required', 'email'],
            'password' => ['sometimes', 'required', 'alpha_num', 'min:8', 'max:20']
        ];

        if ($this->route('id')) {
            $rule['email'][] = Rule::unique('users', 'email')->ignore($this->route('id'));
        } else {
            $rule['email'][] = 'unique:users,email';
        }

        return $rule;
    }

    /**
     * Get the validation attributes that apply to the request.
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'name' => '名前',
            'email' => 'メールアドレス',
            'password' => 'パスワード',
        ];
    }

    /**
     * Get the validation messages that apply to the request.
     *
     * @return array
     */
    public function messages()
    {
        return [
            //
        ];
    }
}

authorizeにreturn backpack_auth()->check();となっている以外は、普通のForm Requestと変わりません。 いつもと同じようにバリデーション記述していきます。
編集時のコンテンツのIDは$this->route('id')で取得できるので、新規作成と編集でメールアドレスのユニークチェックを変更しておきます。

パスワードをハッシュ化する

編集時はパスワードは任意なので、入力されていない場合は保存しないようにします。
又、入力があった場合はパスワードのハッシュ化を行います。

Http/Controllers/Admin/UserCrudController.php

<?php
    public function update()
    {
        // パスワードの処理
        if (!CRUD::getRequest()->input('password')) {
            CRUD::getRequest()->request->remove('password');
        } else {
            CRUD::getRequest()->input('password', Hash::make(CRUD::getRequest()->input('password')));
        }
  
        // 元のupdateメソッドを実行
        $response = $this->traitUpdate();
  
        return $response;
    }

updateをオーバーライドして、passwordの処理を記述します。
入力された値は、CRUD::getRequest()->input()で取得・設定できます。

管理画面のパスを変更する

一通り作業が完了したので、最後に管理画面へのパスを変更したいと思います。
デフォルトでは/adminと推測されやすいパスとなっていて、あまりよろしくありません。
必ず変更したほうが良いでしょう。

今回は、backpack-adminと変更したいと思います。
config/backpack/base.phpを変更します。

<?php
return [

    /*
    |--------------------------------------------------------------------------
    | Registration Open
    |--------------------------------------------------------------------------
    |
    | Choose whether new users/admins are allowed to register.
    | This will show the Register button on the login page and allow access to the
    | Register functions in AuthController.
    |
    | By default the registration is open only on localhost.
    */

    'registration_open' => env('BACKPACK_REGISTRATION_OPEN', env('APP_ENV') === 'local'),

    /*
    |--------------------------------------------------------------------------
    | Routing
    |--------------------------------------------------------------------------
    */

    // The prefix used in all base routes (the 'admin' in admin/dashboard)
    // You can make sure all your URLs use this prefix by using the backpack_url() helper instead of url()
    'route_prefix' => 'backpack-admin',  //ここを変更する

];

route_prefixを変更するだけで完了です。

まとめ

今回でユーザー管理の機能を完成させることができました。一からの開発に比べて、より簡単かつ迅速に機能を構築することが可能だった点はとても助かります。
次回の投稿では、さらに進んで、より多くのカスタマイズオプションを提供するLaravel Backpack PROについて書きたいと思います。