1

Just learning Laravel and found that in Laravel's quick start guide, they suggest for a "delete" request, you can spoof the method as if it is "delete" rather than GET or POST by doing this:

{{ method_field('DELETE') }}

Which generates this html:

<input type="hidden" name="_method" value="DELETE">

And in Laravel back end let's you use the router like this:

Route::delete('/task/{task}', function (Task $task) {
    // do something here
});

But the question is, why do that when I can just set the action of the form to '/task/delete' and use this in the back end:

Route::post('/task/delete/{task}', function (Task $task) {
    // do something here
});

No magic 'spoofing' and more consistent, so any reason to spoof?

Andrew
  • 13,934
  • 8
  • 78
  • 93

2 Answers2

6

The biggest difference is one is RESTful and the other is not. REST uses the method of the request as a verb to describe the type of action being taken. The URI of the object describes the resource the action should be taken on. Laravel utilizes method spoofing because form elements can't use methods other than GET and POST, while other clients like cURL can. You don't have to use the REST approach, especially if no one else is going to connect to your backend.

rexw
  • 221
  • 1
  • 5
  • I upvoted as this describes the reason (which the OP asked for) better, than @Matey's answer. Route::resource is just convenience. – Stefan Oct 09 '17 at 16:25
  • 1
    See [the documentation](https://laravel.com/docs/5.5/routing#form-method-spoofing) – Stefan Oct 09 '17 at 16:30
  • Thank you feeling smarter now. :) This was also useful: https://stackoverflow.com/questions/671118/what-exactly-is-restful-programming – Andrew Oct 10 '17 at 03:11
2

Compare this:

Route::post('/task/delete/{task}', 'TaskController@destroy');
Route::post('/task/put/{task}', 'TaskController@update');
Route::post('/task/post/{task}', 'TaskController@store');
Route::get('task/get/{task}', 'TaskController@show);

To this:

Route::resource('/task', 'TaskController')

Which one looks clearer, more organized and easier to maintain to you?

Matey
  • 1,140
  • 5
  • 7
  • alright I see, the spoofed methods are built into these other magical routes https://laravel.com/docs/5.5/controllers#resource-controllers – Andrew Oct 09 '17 at 15:58
  • obviously looks cleaner, but requires memorizing/looking up what routes are added/handled automatically & using/knowing the default method names for the controllers if you want to modify what they do, and using spoofing, hmm not convinced – Andrew Oct 09 '17 at 15:59