4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel で CollectionからLike検索をする

Last updated at Posted at 2019-11-20

現在Laravelで一覧表示の結果をキャッシュしており、そこから検索できたら、クエリを発行せずに済むので試してみました。

検索はクエリパラメータを取得し行います

実際は複数カラムでのAND検索がしたかったのですが、思い浮かばず断念しました。

1.一覧画面の表示

まずは、ユーザーを全件取得し、viewに渡しています。

SampleController

    // 一覧表示画面
    public function index()
    {
        $users = Cache::rememberForever('users.all', function () {
            return User::all();
        });
        return view('sample',compact('users'));
    }

viewでは表示しているだけです。

sample.blade.php


@forelse ($users as $user)
    <tr>
        <td>{{$user->id}}</td>
        <td>{{$user->name}}</td>
    </tr>
@empty
@endforealse



2.検索エリア作成

form追加しただけです。

sample.blade.php

<form action="#" method="GET">
<input type="text" placeholder="名前" name="name">
<input type="submit" value="検索">
</form>

@forealse ($users as $user)
    <tr>
        <td>{{$user->id}}</td>
        <td>{{$user->name}}</td>
    </tr>
@endforealse


3.検索処理

クエリパラメータの存在を確認し、ユーザー全件をfilterにかけます。
trueのものだけ返却されるので、strposでユーザー名に対して入力された名前のがあるか確認します。
あとはfilterされた結果が入るので一覧表示すれば、絞り込みになります。

SampleController

    // 一覧表示画面
    public function index(Request $request)
    {
        $users = Cache::rememberForever('users.all', function () {
            return User::all();
        });
        // クエリパラメータが空じゃなくある場合
        if ($request->filled('name')) {
            $users = $users->filter(function ($user) use ($request) {
                return strpos($user->name, $request->name) !== false;
            }
        }


        return view('sample',compact('users'));
    }

おわりに

本当はこれをベースに複数項目でのAND検索がしたかったのですが、
上手い書き方が思いつかず...
別途良い方法がありましたらご教授いただけますと幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?