0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Laravel × AdminLTE × Viteで必須項目に赤い「*」を表示する方法

Posted at

LaravelでAdminLTEを使ったフォーム画面で「必須項目に赤い*を付けたい」との要望が。

簡単だろと思っていたがCSSは苦手、、、
案の定、全然反映されない。。。

明日しっかりとスタートダッシュを切るために調べた。
これで反映されなかったら、、、すみません。

前提

  • Laravel
  • laravel-adminlte パッケージ導入済
  • Bladeで @extends('adminlte::page') を使用

1. カスタムCSSを追加

プロジェクト直下の resources/css/custom.css を作成し、以下を記述。

form label.required::after {
  content: "*";
  color: red;
  margin-left: 4px;
  font-weight: bold;
}

2. Bladeで読み込む

Bladeテンプレート内で、AdminLTEのCSS読み込み後にカスタムCSSを呼び出す。

@section('css')
  @vite(['resources/css/custom.css'])
@endsection

※ AdminLTEの page.blade.php は、この @section('css')<head> 内に自動挿入してくれるらしい。


3. HTMLにクラスを付与

必須項目のラベルに required クラスを付けるだけでOK。

<div class="form-group">
  <label for="email" class="required">メールアドレス</label>
  <input type="email" id="email" name="email" required>
</div>

反映されないときの対処

  1. 読み込み順
    AdminLTE本体の後に読み込まれているか確認する。

  2. セレクタ強化
    詳細度を上げて上書きしやすくする。

    .form-group label.required::after {
      /* より強いセレクタ指定 */
    }
    
  3. 最終手段:!important

    form label.required::after {
      color: red !important;
    }
    
  4. デベロッパーツール
    Chromeなどで「検証ツール」→「Styles」を確認し、どのルールが適用・競合しているか調べる。


全ページ共通で読み込む方法

毎回書くのが面倒なら、独自レイアウトを作成する。

{{-- resources/views/layouts/adminlte-vite.blade.php --}}
@extends('adminlte::page')

@push('css')
  @vite(['resources/css/custom.css'])
@endpush

各画面では次のように継承させる。

@extends('layouts.adminlte-vite')

まとめ

手順 内容
CSS追加 resources/css/custom.css に必須マーク用のスタイルを書く
読み込み Bladeで @vite(['resources/css/custom.css']) を設定
クラス付与 <label class="required">…</label> を追加
効かないとき セレクタ詳細度 or !important を調整

Bladeで読み込んでなかったな。。。。
多分bladeの知識も浅いからなのかも。
bladeについても今度調べてみよう。
明日は金曜!バシッと終わらせてこよう!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?