How to delete a single record in Laravel 5?

2019-06-18 04:18发布

问题:

Using Laravel 5 I m trying to delete a single record within a controller, here is my code:

public function destroy($id)
{
     $employee = Employee::find($id);
     $employee->delete();
     return Redirect::route('noorsi.employee.index');
}

My view page code is:

<td><a href="employee/{{$employee->id}}/destroy" class="btn btn-default">Delete</a></td>

My route is:

Route::delete(employee.'/{id}', array('as' => 'noorsi.employee.destroy','uses' => Employeecontroller.'@destroy'));

That did not work.

How do I fix the implementation ?

回答1:

From the official Laravel 5 documentation:

Delete an existing Model

$user = User::find(1);
$user->delete();

Deleting An Existing Model By Key

User::destroy(1);
User::destroy([1, 2, 3]);
User::destroy(1, 2, 3);

In every cases, the number between brackets represents the object ID, but you may also run a delete query on a set of models:

$affectedRows = User::where('votes', '>', 100)->delete();

http://laravel.com/docs/5.0/eloquent#insert-update-delete



回答2:

So the Laravel's way of deleting using the destroy function is

<form action="{{ url('employee' , $employee->id ) }}" method="POST">
    {{ csrf_field() }}
    {{ method_field('DELETE') }}
    <button>Delete Employee</button>
</form>

You can find an example here http://laravel.com/docs/5.1/quickstart-intermediate#adding-the-delete-button And your route should look something like this

Route::delete('employee/{id}', array('as' => 'employee.destroy','uses' => 'Employeecontroller@destroy'));

It works with eg:Route::resource('employee', 'EmployeeController'); and it should also work with how you set up your destroy route.



回答3:

Obviously you have a bad routing problem. You're trying to use a 'get' verb to reach a route defined with a 'delete' verb.

If you want to use an anchor to delete a record, you should add this route:

Route::get('/employee/{id}/destroy', ['uses' => 'EmployeeController@destroy']);

or keep using a delete verb, but then you need to use a form (not an anchor) with a parameter called _method and value 'delete' stating that you're using a 'delete' verb.



回答4:

  Route::get('/showcon/{del_id}/delete','MainController@deletemsg');
  public function deletemsg($del_id){

  $mail=Mail::find($del_id);

  $mail->delete($mail->id);

  return redirect()->back(); 
  }

  <a href="showcon/{{$m->id}}/delete">del</a>