laravel 6 calling post route to return to the same page for sorting table

Viewed 235

I am trying to create a table which the user can sort

I created the following two routes

 route::get('/manager', 'Manager\DeadlineController@index')->middleware(['auth', 'auth.manager'])->name('manager.index');
    route::post('/manager/{name_id}', 'Manager\DeadlineController@sortByName')->middleware(['auth', 'auth.manager'])->name('manager.sortByName');

from my php artisan route:list

|        | GET|HEAD  | manager                      | manager.index        | App\Http\Controllers\Manager\DeadlineController@index                  | web,auth,auth.manager |
|        | POST      | manager/{name_id}            | manager.sortByName   | App\Http\Controllers\Manager\DeadlineController@sortByName             | web,auth,auth.manager |

and set up my controller as follows

public function index()
{
    return view('deadline.index')
    ->with([
        'modules' => Module::all(),
        'name_id' => 0
    ]);
}

public function sortByName($name_id){
    if($name_id == 0){
        $sortedModule = Module::orderBy('name', 'DESC')->get();
    }
    else{
        $sortedModule = Module::orderBy('name', 'ASC')->get();
    }

    return view('deadline.index')
    ->with([
        'modules' => $sortedModule,
        'name_id' => 1
    ]);
}

in my view i use the following link to sort

 <th scope="col"><a href="{{ route('manager.sortByName', $name_id) }}">NAME</a></th>

but when i use this link in my view I am somehow redirected to my GET route because i get the following error

The GET method is not supported for this route. Supported methods: POST.

What am I missing or doing wrong? Any help or tips will be appreciated. Please ask if I need to provide more details

Update

I change the link in my view to a form tag with a submit button and now it works

<th scope="col">
   <form action="{{ route('manager.sortByName', $name_id) }}" method="POST">
         @csrf
         <button type="submit">NAAM</button>
    </form>
</th>
1 Answers

When you click on <a> tag it does GET request, so you need to change your route from POST to GET, also returning view as a response to post method is not good idea,the best solution is GET route

Related