LoginSignup
1
0

More than 1 year has passed since last update.

Laravel + Vue3 + Inertia のconst, config定義を極めた

Last updated at Posted at 2022-10-03

自動補完されたいからちゃんと class hoge に const FUGA = 1; として実装したいし
でもconfig('hoge.FUGA')で取得したいし
でもvueでも使わないといけない、雑にぐぐるとvueはvueでjsに定義してたりする
すざけるな^^

昔は全部DBでマスタ管理してたなぁ懐かしい

Model/Hoge.php
class Hoge extends Model
{
    const FUGA = 1;
    const PIYO = 2;
    const POKO = 3;
    const METAVARS = [
        self::FUGA = 'ふが',
        self::PIYO = 'ぴよ',
        self::POKO = 'ぽこ',
    ];
}
config/const.php
return [
    'hoge' => (new ReflectionClass(Hoge::class))->getConstants(),
];
Http/Middleware/HandleInertiaRequests.php
public function share(Request $request)
{
    return array_merge(parent::share($request), [
        'const' => config('const'),
    ]);
}
resources/js/Pages/Hoge.vue
<template>
    <select>
        <option v-for="(label, id) in const.hoge.METAVARS" :value="id">{{ label }}</option>
    </select>
</template>
<script>
export default {
    computed: {
        const(){ return this.$attrs.const; }
    }
}
</script>

少なくとも、自分が雑に検索して出てきた色々な定数定義ハウツーよりもシンプルでマシだと思うんだけど
もっといい方法あったら教えてください

あと vue3 の setup がまだよくわかってないのでまたこれから勉強します

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