EtDes
EtDes

Reputation: 85

Directly access a put/update method on Laravel 5.1 without going into the edit view (MethodNotAllowedHttpException in RouteCollection.php error)

I wanted to disable employees from a button on my index.blade.php page. Currently, the options of disabling employees (setting the status column in the database to false) is either to have an edit.blade.php view and update the value there, which is pretty standard for any laravel app or to have a new view for example, changestatus.blade.php, with the proper routes offcourse and update the value there. I am using the second implementation and it's working perfectly.

What i wanted to implement is to have a button on the index page which will change the status of the employee without going to a edit.blade.php or changestatus.blade.php page.

What i have tried I have created new routes and created a button to link to the changestatus function

Routes.php

Route::put('employees/{employee}/changestatus', 'EmployeesController@changestatus')->name('employees.changestatus');
Route::resource('employees', 'EmployeesController');

EmployeeController

public function changestatus($EmployeeID)
{        
    $employee = Employee::find($EmployeeID);
    $employee->status = true;
    $employee->Save();        
}

On my view i created a button with the following link

{{ URL::route('employees.changestatus', $employee->EmployeeID) }}

When i click that link, i get the MethodNotAllowedHttpException in RouteCollection.php error.

I even tried to change the Route::put to Route::Patch, but it's the same thing. Is it even possible to achieve what I'm trying to do? If so, how?

Upvotes: 1

Views: 1139

Answers (1)

edcs
edcs

Reputation: 3879

When you click on a hyperlink, the web browser submits a GET request. Your route has been defined as being a PUT so that's why you're getting an exception.

You could either change the route to a GET by defining it like this:

Route::get('employees/{employee}/changestatus', 'EmployeesController@changestatus')->name('employees.changestatus');

Which isn't very ReSTful since a GET request should really only be used for returning a resource rather than modifying it.

Or, you could modify the button so that it submits a form like this:

<form method="post" action="{{ route('employees.changestatus', $employee->EmployeeID) }}">
    {{ method_field('PUT') }}
    <button type="submit">Button Text</button>
</form>

Note that you can't simply set the form method to PUT since this method isn't generally supported by web browsers. Laravel supports method spoofing which you can read all about here:

http://laravel.com/docs/5.1/routing#form-method-spoofing

Upvotes: 0

Related Questions