I'm learning laravel and I'm having a problem with one route:
Route::post('/sortby/{id}', [GuestBook::class, 'Sort'])->name('sort');
Function implementation:
public function Sort($val = 0, Request $request)
{
$type = '';
foreach ($request->except('_token') as $key => $value) {
$type = $key;
}
$pag_num = 10;
$data = guest_table::where('is_pub', 1);
switch ($type) {
case 'byid':
$data = $data->orderBy('id', 'asc')->paginate($pag_num);
break;
case 'byidDesc':
$data = $data->orderBy('id', 'desc')->paginate($pag_num);
break;
case 'byemail':
$data = $data->orderBy('email', 'asc')->paginate($pag_num);
break;
case 'byemailDesc':
$data = $data->orderBy('email', 'desc')->paginate($pag_num);
break;
case 'byusername':
$data = $data->orderBy('username', 'asc')->paginate($pag_num);
break;
case 'byusernameDesc':
$data = $data->orderBy('username', 'asc')->paginate($pag_num);
break;
case 'bydate':
$data = $data->orderBy('created_at', 'asc')->paginate($pag_num);
break;
case 'bydateDesc':
$data = $data->orderBy('created_at', 'desc')->paginate($pag_num);
break;
default:
break;
}
return view('posts', ['data' => $data]);
}
So, when I process a post request for sorting by certain fields, I get a redirect to http://127.0.0.1/sortby/0.
When I use the paginator I get the link http://127.0.0.1:8000/sortby/0?page=2 and gives me the error the GET method is not supported for this route.
I understand that when I navigate to http://127.0.0.1:8000/sortby/0?page=2, a get request is sent from me, but I don't know how to solve it(
CodePudding user response:
You have post
route on Route::post('/sortby/{id}', [GuestBook::class, 'Sort'])->name('sort');
. That's why you are receiving this error.
Just change it to:
Route::get('/sortby/{id}', [GuestBook::class, 'Sort'])->name('sort');
This might throw an error if you are sending the request to http://127.0.0.1/sortby/0
as a post
request, at the first time, you have to change it on the front end as well, and need to send it as a get
request instead.