category

category

laravel

2025.7.21

2025.7.21

36

【Laravel】検索ページで、検索結果の件数を表示し、0件の場合は「見つかりませんでした」と表示する

表示イメージ

※全て同じページ(URL)

ルーティング

Route::get('search', 'App\Http\Controllers\コントローラ名@find');
Route::post('search', 'App\Http\Controllers\コントローラ名@search');

※アドレスは「search」(何でもOK)

コントローラ

public function find(Request $request){
    return view('ビューテンプレート名',['input'=>'','count'=>0]);
}

public function search(Request $request){
    $items = モデル名::where('検索対象のカラム名', 'LIKE', "%{$request->search_input}%")->get();
    $count = (count($items)>0) ? count($items) : 0;
    $param = ['input'=>$request->search_input, 'items'=>$items, 'count'=>$count];
    return view('ビューテンプレート名',$param);
}

※検索はあいまい検索(検索対象カラムに検索文字列が含まれているかどうか)

※$countに検索結果の件数を格納している

ビューテンプレート

@section('content')
    <p class="title">検索</p>
    <form action="{{url('')}}/search" method="post">
        @csrf
        検索ワード<input type="text" name="search_input" value="{{$input}}" required /><br />
        <input type="submit" value="検索する">
    </form>

    @if(isset($items))
        @if($count === 0)
            <p class="nodata">見つかりませんでした。</p>
        @else
        <table>
            <tr>
                <th>ID</th>
                <th>項目名</th>
                <th>項目</th>
                <th>項目</th>
                <th></th>
            </tr>
            @foreach ($items as $item)
                <tr>
                    <td>{{$item->id}}</td>
                    <td>{{$item->カラム名}}</td>
                    <td>{{$item->カラム名}}</td>
                    <td>{{$item->カラム名}}</td>
                    <td>
                        <ul>
                            <li><a href="{{url('')}}/edit?id={{$item->id}}">修正</a></li>
                            <li><a href="{{url('')}}/del?id={{$item->id}}">削除</a></li>
                        </ul>
                    </td>
                </tr>
            @endforeach
        </table>
        <p>{{$count}}件見つかりました。</p>
        @endif
    @endif
@endsection
970

コメント

コメントを残す

ニックネームは公開されます

CAPTCHA


閉じる