Romário Carvalho
Romário Carvalho

Reputation: 31

Search and Pagination Laravel 4

I have a problem, I want to use the form to do a search and use pagination. The problem is when I change the page, an error occurs:

No query results for model [Aluno].

My controller

Route::post(
'alunos/busca', 
array(
    'as' => 'alunos.busca', 
    'uses' => 'AlunosController@busca'
)

);

My Controller

public function busca()
{
   $search = Input::get('q');
   $alunos = Aluno::where('curso', $search)->paginate(1);
   return View::make('alunos.index', compact('alunos', 'search'));
}   

My view:

<form method="post" action="{{ URL::to('alunos/busca') }}">
<input class="input-xxlarge" name="q" type="text" placeholder="Search...">
<div class="control-group">
    <div class="controls">
        <input type="submit" class="btn" id="submit" value="Submit" />
    </div>
</div> 
<div class="divPagination">
   {{ $alunos->links() }}
</div>

I need help..

Sorry my English

Upvotes: 2

Views: 282

Answers (2)

Xavi Mart&#237;nez
Xavi Mart&#237;nez

Reputation: 2161

I think the best solution is the next one:

  1. Copy and paste this form wherever you want it:

    {{Form::open(array('url' => 'alunos/busca','method' => 'get'))}}
    {{Form::text('q', null , array('placeholder' => 'Search...','class' => 'input-xxlarge'))}}
    {{Form::submit('SEARCH',array('class' => 'btn','id' => 'submit'))}}
    {{Form::close()}}
    
  2. In routes.php :

    Route::get('alunos/busca', function() {
       $search = Input::get('q');
       $alunos = Aluno::where('curso', 'LIKE', '%'.$search.'%')->paginate(15);
       return View::make('alunos.index')
        ->with('alunos', $alunos);
    });
    
  3. Now, in your view app/views/alunos/index.blade.php :

    @if(!$alunos->isEmpty())
       @foreach($alunos as $aluno)
          {{$aluno->subject}}
       @endforeach
    
     {{$alunos->links()}}
    
    @else
       <h1> No results </h1>
    @endif
    
  4. Change it as you wish and enjoy

Upvotes: 1

bgallagh3r
bgallagh3r

Reputation: 6086

The problem is when you click on the next page it has no memory of the search param you just entered, essentially $q = null; which will cause the error.

Upvotes: 0

Related Questions