Laravel - Searching from two tables and combining the result

Posted: 26-05-2019 | Views: 173
Laravel - Searching from two tables and combining the result

Searching from two tables (Post and Lecture) and combining the result.

1) routes->web.php

Route::post('/search',function(){
    $q = Input::get ( 'q' );
    $post = App\Post::where('title','LIKE','%'.$q.'%')->get();
    $lecture = App\Lecture::where('title','LIKE','%'.$q.'%')->get();
    $merged = $post->merge($lecture);
    if(count($merged) > 0){
        return view('searchResult')->withDetails($merged)->withQuery ( $q );
    }
    else {
        return view ('searchResult')->withMessage('No Details found. Try to search again !');
    }
});

2) resources->views->searchresult.blade.php

<form class="navbar-form navbar-left" role="search" action="/search" method="POST">
          {{ csrf_field() }}
      <div class="input-group">
        <input type="text" class="form-control" placeholder="Search" name="q">
        <div class="input-group-btn">
          <button class="btn btn-default" type="submit">
            <i class="glyphicon glyphicon-search"></i>
          </button>
        </div>
      </div>
 </form>

and

@if(isset($details))
    <h3> The Search results for your query <code> {{ $query }} </code> are :</h3>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Title</th>
            <th>Slug</th>
            <th>Image</th>
            <th>Download</th>
            <th>Created</th>
        </tr>
    </thead>
    <tbody>
        @foreach($details as $result)
        <tr>
            <td>{{$result->title}}</td>
            <td><a href="/post/{{$result->slug}}" target="_blank">{{$result->slug}}</a></td>
            <td><img src="{{ Voyager::image( $result->image ) }}" width="100"/></td>
            @if($result->path)
            <td><a href="/yourstoragefolder/{{$result->path}}" download>Download</a></td>
            @else
            <td>Not available</td>
            @endif
            <td>{{$result->created_at}}</td>
        </tr>
        @endforeach
    </tbody>
</table>
@endif

Add comment