JS_LnMstr
JS_LnMstr

Reputation: 378

Laravel Pagination on POST request

Im using Laravel v7 and i have a question about pagination.

So far im using 2 routes, 1rst to return a view with all rows from database, and 2nd receives an input and returns that view with the rows filtered by that input value.

But im using pagination, and on the 2nd route, when i try to go to 2nd page it gives me an error:

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.

I've tried to change my form method to GET but i need that the token doesn't appear on the page URL and beside that, when i go to 2nd page, it returns all the rows again.

Thats my code so far:

Routes:

Route::get('concessions', 'ConcessionController@index')->name('concessions.index');
Route::post('concessions/search', 'ConcessionController@search')->name('concessions.search');

Controller

class ConcessionController extends Controller
{
    public function index()
    {
        $concessions = DB::table('concessions')->paginate(12);

        return view('admin.concessions.index', compact('concessions'));
    }

    public function search(Request $request)
    {
        $name = $request->name;

        $concessions = Concession::where('name', 'like', '%' . $name . '%')->paginate(12);

        return view('admin.concessions.index', compact('concessions', 'name'));
    }
}

Any way to do that?

Upvotes: 3

Views: 4193

Answers (2)

Amin Mashayekhan
Amin Mashayekhan

Reputation: 603

From my perspective, if you change your route code similar to below code, it will work properly with both methods of GET and POST.


Route::any('concessions/search', 'ConcessionController@search')->name('concessions.search');

Upvotes: 6

STA
STA

Reputation: 34688

Laravel pagination only works with get parameters.

You should use GET method for your search page. POST requests aren't meant for the purpose of displaying data. Why? There are many reasons, but to be short I will give you three examples :

1. When you access the first page, you get the data by GET request, not POST request. So if you want to use POST request, you need to access the page as POST request by sending data with POST method.

2. With GET parameters, let's say you are on 5th page - you can copy the link and paste it to friend and he will be able to view the same content as you. With POST this is impossible.

3. You can not use back button with POST requests, if you manage to get pagination to work.

POST requests are useful when you need to submit data to the server, in order to create new record, for example.

So I suggest you to change your route type to GET.

Upvotes: 7

Related Questions