7
7

More than 3 years have passed since last update.

【Laravel】複数条件のキーワード&絞り込み検索フォームを作る。(複数テーブルから取得)

Last updated at Posted at 2020-04-16

はじめに。出来上がりはこんな感じ。
スクリーンショット (18).png

やりたいこと

  • laravelで検索フォームを作る
  • 曲名とアーティスト名を入力したらキーワード検索&絞り込みしてDBから取得する

前提

  • データベースは作成済みとして進めます

進めかた

  • テーブルの作成
  • Controllerの作成
  • viewの作成

テーブル構成

artistsテーブル

id name

songsテーブル

id name artist_id

Controller

SongController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use \App\Song;
use \App\Artist;

class SongController extends Controller
{
    public function search(Request $request){
      //フォームから送られてきた値を取得
       $song_keyword = $request->input('song_keyword');
       $artist_keyword = $request->input('artist_keyword');
      //ふたつの値が空じゃないか判定
       if(!empty($song_keyword) && !empty($artist_keyword)){
      //もし空じゃなけれDBからlikeを使ってキーワード検索
          $song   = Song::where('name','like','%'.$song_keyword.'%')->first();
          $artist = Artist::where('name','like','%'.$artist_keyword.'%')->first(); 
          //キーワード検索して該当するデータが2つともあるならidを取得      
          if($song && $artist){
             $song = $song->id; 
             $ids  = $artist->id;
      //songsテーブルのidに$songと同じidがあり、かつartist_idに$idsと同じidがあるカラムを検索し取得
             $song = Song::where('id',$song)->where('artist_id',$ids)->orderBy('id','asc')->paginate(30);
      //検索結果の$songが空じゃないか判定(ここではCollection配列になるのでisEmpty()で判定する
             if($song->isEmpty()){
       //空ならnullをviewに渡す
                return view('song.song_find',['songs'=>null,'song_keyword'=>$song_keyword,'artist_keyword'=>$artist_keyword]);
                }
          //空じゃなかったら値をviewに渡す
              return view('song.song_find',['songs'=>$song,'song_keyword'=>$song_keyword,'artist_keyword'=>$artist_keyword]);
             }
          //キーワード検索して該当するデータが2つ揃わなかったらnullをviewに渡す
            return view('song.song_find',['songs'=>null,'song_keyword'=>$song_keyword,'artist_keyword'=>$artist_keyword]);
         //フォームから送られてきた値が楽曲だけの場合の処理
        }else if(!empty($song_keyword)){
            $song = Song::where('name','like','%'.$song_keyword.'%')->orderBy('id','asc')->paginate(30);
            if($song->isEmpty()){
                return view('song.song_find',['songs'=>null,'song_keyword'=>$song_keyword,'artist_keyword'=>'']);
            }else{
                return view('song.song_find',['songs'=>$song,'song_keyword'=>$song_keyword,'artist_keyword'=>'']);
            }
      //フォームから送られてきた値がアーティスト名だけの場合の処理
        }else if(!empty($artist_keyword)){
            $artist = Artist::where('name','like','%'.$artist_keyword.'%')->first();
           if($artist){
                $ids = $artist->id;
                $artist = Song::where('id_artist',$ids)->orderBy('id','asc')->paginate(30);
            }
        return view('song.artist_find',['artists'=>$artist,'artist_keyword'=>$artist_keyword,'song_keyword'=>'']);
        }
    }

正直if文使いすぎてわけが分かりません。。w

viewの作成

song/song_find.blade.php
@extends('layouts.ksongapp')
@section('title', '楽曲検索詳細')
@section('content')

<div class="page-header" style="margin-top:-30px;padding-bottom:0px;">
    <h1><small>楽曲検索詳細</small></h1>
    <form class="form-horizontal find" action = "{{ url('/') }}/song/find" method="post"  class="form-horizontal">
    @csrf
        <div class="form-group">
           <input type="text" name="song_keyword" value="{{$song_keyword}}" >
           <input type="submit" value="検索" >
        </div>
        <div class="form-group">
           <input type="text" name="artist_keyword" value="{{$artist_keyword}}" placeholder="アーティスト名を入力">
           <input type="submit" value="検索" >
        </div>
    </form>
</div>
<div class="songs">
   @if(!empty($songs))
   <table class="table table-striped table-hover">
      <tr>
          <th>楽曲ID</th><th>楽曲名</th><th>アーティスト名</th>
      </tr>
      @foreach($songs as $song)
          <tr>
              <td>{{$song->id}}</td>
              <td><a href="{{ url('/') }}/song/show?id={{$song->id}}" >{{$song->name}}</a></td>
              <td><a href="{{ url('/') }}/artist/show?id={{$song->artists->id}}" >{{$song->artists->name}}</a></td>
              <td>
              <button class="btn btn-warning btn-sm" onclick="location.href='{{ url('/') }}/song/show?id={{$song->id}}'">詳細</button>
              <button class="btn btn-primary btn-sm" onclick="location.href='{{ url('/') }}/song/edit?id={{$song->id}}'">編集</button>
              <button class="btn btn-danger btn-sm btn-dell" onclick="location.href='{{ url('/') }}/song/del?id={{$song->id}}'">削除</button>
              <button class="btn btn-success btn-sm " onclick="location.href='{{ url('/') }}/song/csv?id={{$song->id}}'">CSVダウンロード</button>
              </td>
           </tr>
       @endforeach
    </table>
    @else
        <p>データがみつかりません</p>
    @endif
</div>
@endsection

song/artist_find.php
@extends('layouts.ksongapp')
@section('title', '楽曲検索詳細')
@section('content')

<div class="page-header" style="margin-top:-30px;padding-bottom:0px;">
   <h1><small>楽曲検索詳細</small></h1>
   <form class="form-horizontal find" action = "{{ url('/') }}/song/find" method="post"  class="form-horizontal">
    @csrf
       <div class="form-group">
          <input type="text" name="song_keyword" value="{{$song_keyword}}" >
          <input type="submit" value="検索" >
       </div>
       <div class="form-group">
          <input type="text" name="artist_keyword" value="{{$artist_keyword}}" placeholder="アーティスト名を入力">
          <input type="submit" value="検索" >
       </div>
    </form>
</div>

<div class="songs">
    @if(isset($artists))
    <table class="table table-striped table-hover">
        <tr>
            <th>アーティスト</th><th>楽曲ID</th><th>楽曲名</th>
        </tr>
        @foreach($artists as $artist)
            <tr>
                <td><a href="{{ url('/') }}/artist/show?id={{$artist->artists->id}}" >{{$artist->artists->name}}</a></td>
                <td>{{$artist->id}}</td>
                <td><a href="{{ url('/') }}/song/show?id={{$artist->id}}" >{{$artist->name}}</a></td>
                <td>                
                <button class="btn btn-warning btn-sm" onclick="location.href='{{ url('/') }}/song/show?id={{$artist->id}}'">詳細</button>
                <button class="btn btn-primary btn-sm" onclick="location.href='{{ url('/') }}/song/edit?id={{$artist->id}}'">編集</button>
                <button class="btn btn-danger btn-sm btn-dell" onclick="location.href='{{ url('/') }}/song/del?id={{$artist->id}}'">削除</button>
                <button class="btn btn-success btn-sm " onclick="location.href='{{ url('/') }}/song/csv?id={{$artist->id}}'">CSVダウンロード</button>
                </td>
            </tr>
        @endforeach
    </table>
    @else
    <p>データがみつかりません</p>
    @endif
</div>
@endsection

以上です。Collectionの返り値の判定に苦労しました。。

7
7
1

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