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 ?
Step 1: Create Controller UserController by executing this command. Step 2: We can delete records in two ways. Second Method: The second way is to delete using the Laravel delete Function and User Model (Easy one). ->name( 'users.
Laravel Eloquent Deleting To delete a model instance, retrieve it and call the delete() method: $user = User::find(1); $user->delete(); Alternatively, you can specify a primary key (or an array of primary keys) of the records you wish to delete via the destroy() method: User::destroy(1); User::destroy([1, 2, 3]);
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With