简体   繁体   中英

spoofing request method in laravel action() helper method?

In a Laravel 5.5 project, I have a student controller with destory method.

public function destroy(Student $student)
{
    //destroy $student and redirect
}

I have the route for the controller as follows

Route::delete('/student/{id}', 'StudentController@destroy');

Now let's get to the question.

I have a page to manage students and it has a delete button.

  <a class="btn btn-danger"
       href="{{ action('StudentController@destroy', ['id' => $student->id]) }}" >
  Delete
  </a>

when i click the delete button it throws method not allowed exception since the request is not a delete request. Is there any way/workaround to specify/spoof the request method through action()/route() helper functions?

Normally I would have created a form with a hidden _method="delete" input and post the form. but if I am adding an update button, then I would have to create another form with a hidden _method="patch" in it and I don't think this is a good practice.

please give some ideas to go forward.

Answering your question - yes, you should create form that will allow you to delete the student. This is how REST should be used - you don't create workarounds but you just use valid HTTP method for given action.

There is also one other reason why you shouldn't use links and GET methods for this. For example let's assume your URL to remove student looks like this:

http://example.com/students/1/delete

When you type url in browser, browsers usually remember previous urls, so you could remove some student by mistake if you used GET method to remove students.

Of course in above example you could use JavaScript that will be launched when you click the link that will run valid HTTP action, but it might mean more work than using simple form.

There are 2 ways that I can think of it:

  1. Create a form with method DELETE

     {!! Form::model($student, ['method' => 'DELETE', 'action' => ['StudentController@destroy', $student->id]]) !!} {!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!} {!! Form::close() !!} 
  2. Create an ajax request with request type DELETE

     $.ajax({ url: '/students/'+id+'/delete, type: "DELETE", data:{ _token: "{{ csrf_token() }}" } }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM