Friday, March 17, 2017

search query not working in laravel

I need to return the results of what the user write in the search bar, but when i press search to test it nothing happens.

this is how i created the search bar

<form class="form-inline" role="search" action="" method="POST">
    
    <div class="form-group">
        <input type="text" class="form-control" name="searchbar" placeholder="Find a source!">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
</form>

in my controller i have the following code to find what the user has entered in the search bar. It searches the datebase for a title thats like whats written in the search bar. If nothing is found it return's an error (this is working). if a row higher than 0 return it need to bring that result back to the page

public function searchSource(Request $request){
    $this->validate($request,[
        'searchbar' => 'required',
    ]);

    $find = $request['searchbar'];

    $query = Source::where('title','LIKE', '%'.$find.'%')->where('user_id', Auth::user()->id)->get();

    if(count($query) > 0) {
        return redirect()->route('sources-index')->with(['query' => $query]);
    }else{
        return redirect()->route('sources-index')->with('customerror', 'nothing found, try a different searchterm.');
    }
}

back on the page it need to get the result if there is asked for a searchterm, else it need to give everything of the database

@if(!empty($uery))
    @foreach($query as $querys)
        <tr>
            <td class="source-cell">
                
            </td>

            <td>
                
            </td>

            <td>
                
            </td>
        </tr>
    @endforeach
@else
    @foreach ($sources as $source)
        <tr>
            <td class="source-cell">
                
            </td>

            <td>
                
            </td>

            <td>
                
            </td>
        </tr>
    @endforeach
@endif

T tried dd() on a couple of places and everything worked fine, except on the page, i tried dd($query) after the if statement nothing happend.

I tried it after the foreach nothing happend.

But when i tried it before the if statement i got an error

Undefined variable: query (View: ...\resources\views\sources\index.blade.php)

What am i doing wrong.



via Peter Arents

Advertisement