LoginSignup
4
3

More than 1 year has passed since last update.

【Laravel Livewire】俺的住所検索ベストプラティクス

Last updated at Posted at 2022-09-01

はじめに

以前こんな記事を書いた。

「うーん気持ち悪いなぁ」と思いながら対応した記憶がある。

理想は

  1. 郵便番号を入力
  2. 検索ボタンクリック
  3. 都道府県とかをセット。

というフローが良い。
PHP側に住所検索API処理を書けば綺麗にいけるんじゃねえかと思い,
取り組んだ結果を書いてく。

zipcloud API

yubinbangoは自動入力だったがこちらは任意のタイミングで検索をかけられる。

コードを書く

一旦動きそうな住所取得処理を書きます(処理は適当です、コピペしない方がいいです)

<?php

namespace App\Services;

class AddressApiService
{
    private $base_url = 'https://zipcloud.ibsnet.co.jp/api/search?zipcode=';

    public function __invoke(string $zipCd): array
    {
        $json = file_get_contents($this->base_url . $zipCd);
        $json = mb_convert_encoding($json, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
        $arr = json_decode($json, true);

        if ($arr['results'] === null) {
            $resultArray['message'] = '郵便番号から住所が見つかりませんでした。';
            return $resultArray;
        }
        $resultArray = [];

        if (!empty($arr['message'])) {
            $resultArray['message'] = $arr['message'];
            return $resultArray;
        }

        $resultArray['prefecture'] = $arr['results'][0]['address1'];
        $resultArray['address1'] = $arr['results'][0]['address2'];
        $resultArray['address2'] = $arr['results'][0]['address3'];

        return $resultArray;
    }
}

livewireコンポーネントにはこんな感じの処理を書きます。


    public function setAddress(): void
    {
        $addressApiService = new AddressApiService();
        $addressArray = $addressApiService($this->hoge->zipcd);
        if (!empty($addressArray['message'])) {
            session()->flash('addressErrorMessage', $addressArray['message']);
            return;
        }
        $this->hoge->prefecture = $addressArray['prefecture'];
        $this->hoge->address1 = $addressArray['address1'];
        $this->hoge->address2 = $addressArray['address2'];
    }

Blade側にはボタンか何かにwire:click="setAddress()"って書いておいて
エラーメッセージ用の記述しとけばOKです。多分。

@if(session()->has('addressErrorMessage'))
    <p class="pt-0 col-form-label col-form-label-sm text-danger">
        {{ session()->get('addressErrorMessage') }}
    </p>
@endif

おわり

住所自動入力はlivewireと相性悪いんで任意のタイミングで検索できるzipcloudのAPIを使ってこうと思います。

4
3
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
3