55
59

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 2018-03-12

###やりたいこと

  • 条件を複数指定して検索したい
  • ひとつでも複数でも検索可能に

###追記:コメントから学んだこと
コメントで頂いた書き方を追記しました。
検索方法によってはとてもスマートにコンパクトにできます。

  • Controllerでの値の取得、検索はhasメソッドを使用してコンパクトにできる
  • 検索方法が同じであればonlyメソッドを使用してコンパクトにできる

###View

resources\views\example.blade.php
{!! Form::open() !!}
    タイトル:{!! Form::text('s_title', $s_title) !!}
    カテゴリー:{!! Form::text('s_category', $s_category) !!}
    監督:{!! Form::text('s_production', $s_production) !!}
    出演:{!! Form::text('s_performer', $s_performer) !!}
    {!! Form::submit('検索') !!}
{!! Form::close() !!}
 
@foreach($movies as $movie)
<div>
    <a>{{ $movie->id }}</a>
    <a>{{ $movie->title }}</a>
    <a>{{ $movie->category }}</a>
    <a>{{ $movie->production }}</a>
    <a>{{ $movie->performer }}</a>
</div>
@endforeach

###Controller

app\Http\Controllers\SearchController.php
<?php
 
namespace App\Http\Controllers;
 
use App\Movies;
use Request;
 
class SearchController extends Controller
{
    public function example(Request $request)
    {
        $query = Movies::query();

        //自分の書き方
        // 検索条件の値を取得
        $s_title = $request->input('s_title');
        $s_category = $request->input('s_category');
        $s_production = $request->input('s_production');
        $s_performer= $request->input('s_performer');

        // もし$s_titleがあれば
        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_performer)) {
            $query->where('performer', 'like', '%'.$s_performer.'%');
        }


        //コメントでいただいた書き方
        //hasメソッドを使用(値が存在、かつ空ではないか)
        if($request->has('s_title'))) {
            $query->where('title', 'like', '%'.$request->get('s_title').'%');
        }

       //また、同じ検索条件(今回はwhere)の場合は、onlyメソッドでまとめることができる
       foreach ($request->only(['s_title', 's_category','s_production','s_performer']) as $key => $value) {
           $query->where($key, 'like', '%'.$value.'%');
       }

       $movies = $query->get();

        return view('example', compact('movies'));

    }
}
55
59
2

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
55
59

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?