Laravelで複数の値で検索を行う

前回の記事の続きで、Laravelで複数の値から検索を行ってみます。

サンプルコード

resources\views\search\index.blade.php

{!! Form::open(['method' => 'GET']) !!}
    タイトル:{!! Form::text('s_title', $s_title) !!}
    カテゴリ:{!! Form::text('s_category', $s_category) !!}
    制作会社:{!! Form::text('s_production', $s_production) !!}
    声優:{!! Form::text('s_actor', $s_actor) !!}
    {!! Form::submit('検索') !!}
{!! Form::close() !!}

@foreach($data as $item)
<div>
    <div>{{{ $item->id }}}</div>
    <div>{{{ $item->title }}}</div>
    <div>{{{ $item->category }}}</div>
    <div>{{{ $item->production }}}</div>
    <div>{{{ $item->actor }}}</div>
</div>
<hr>
@endforeach

app\Http\Controllers\SearchController.php

<?php

namespace App\Http\Controllers;

use App\Autumn2016;
use Request;

class SearchController extends Controller
{
    public function getIndex()
    {
        // 検索するテキスト取得
        $s_title = Request::get('s_title');
        $s_category = Request::get('s_category');
        $s_production = Request::get('s_production');
        $s_actor = Request::get('s_actor');
        $query = Autumn2016::query();
        // 検索するテキストが入力されている場合のみ
        if(!empty($s_title)) {
            $query->where('title', 'like', '%'.$s_title.'%');
        }
        if(!empty($s_category)) {
            $query->where('category', 'like', '%'.$s_category.'%');
        }
        if(!empty($s_production)) {
            $query->where('production', 'like', '%'.$s_production.'%');
        }
        if(!empty($s_actor)) {
            $query->where('actor', 'like', '%'.$s_actor.'%');
        }
        $data = $query->get();
        return view('search.index', compact('data', 's_title', 's_category', 's_production', 's_actor'));
    }
}

タイトルを「あ」、カテゴリを「オリジナル」で検索すると、以下のように絞られた状態で表示されました。

search-by-multiple-values-in-laravel01

 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930