26
23

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】検索機能の実装① ~基本!キーワード部分一致検索~

Last updated at Posted at 2021-09-11

作成物

Book Listの一覧から、著書名もしくは著者名が部分一致するレコードを検索する機能を実装します。
スクリーンショット 2021-09-10 20.47.36.png

前提

  • "title" "author" "body" の要素を持つ、Postsテーブル(BoolListの投稿テーブル)を作成済み。
  • SeederでPostsテーブルへサンプルデータを保存済み。

今回実装する機能の概要

  • データを全件表示する一覧画面と、検索結果の一覧表示画面は、同じviewファイル・Controllerのメソッドを使います。
  • 検索boxに何か入力された場合は、Controllerのメソッド内のif文を通ってデータを絞り込み、絞り込んだデータのみを一覧画面のviewに返します。検索boxに何も入力されていない場合は、if文を通らず、データ全件をviewへ返します。

migrationファイルの確認

作成しているmigrationファイルは、以下の通りです。

2021_08_28_064931_create_posts_table.php

/** 略 **/

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('author');
            $table->text('body');
            $table->timestamps();
        });
    }

/** 略 **/

Viewの作成

index.blade.php
//* 検索機能ここから *//
<div>
  <form action="{{ route('posts.index') }}" method="GET">
    <input type="text" name="keyword" value="{{ $keyword }}">
    <input type="submit" value="検索">
  </form>
</div>
//*検索機能ここまで*//

<h1>
  <span>My Book List</span>
  <a href="{{ route('posts.create') }}">[Add]</a>
</h1>

<table>
  <tr>
    <th>著書名</th><th>著者名</th>
  </tr>

//* 保存されているレコードを一覧表示 *//
  @forelse ($posts as $post)
    <tr>
      <td><a href="{{ route('posts.show' , $post) }}">{{ $post->title }}</td></a>
      <td>{{ $post->author }}</td>
    </tr>
  @empty
    <td>No posts!!</td>
  @endforelse
</table>

ルート定義

検索ボタンを押した際のルーティングも、一覧画面の表示と同じPostControllerのindexメソッドに、getメソッドでアクセスします。

web.php
Route::get('/', [PostController::class, 'index'])
    ->name('posts.index');

コントローラーの編集

コントローラーを下記のように編集します。

PostController.php
class PostController extends Controller
{
    public function index(Request $request)
    {
        $keyword = $request->input('keyword');

        $query = Post::query();

        if(!empty($keyword)) {
            $query->where('title', 'LIKE', "%{$keyword}%")
                ->orWhere('author', 'LIKE', "%{$keyword}%");
        }

        $posts = $query->get();

        return view('index', compact('posts', 'keyword'));
    }

コントローラーの解説

  • 検索boxに入力された値を受け取り、$keywordに格納します。
  • $keywordで何かしらの値を受け取った場合は、if文の中で取得するデータを絞りこみます。
  • whereメソッドLIKE検索を指定し、$keywordの両側に%をつけることで、部分一致検索を行います。またorWhereメソッドでOR検索を行います。
  • viewファイルindex.blade.phpへ、posts(一覧表示するデータ)keyword(検索ボックスのvalue値)を受け渡します。




以上です^^

26
23
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
26
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?