Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a single record in Laravel 5?

Tags:

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 ?

like image 334
Si Va Avatar asked Nov 13 '15 07:11

Si Va


People also ask

How do I delete a single record in laravel?

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.

How do I delete a record in laravel eloquent?

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]);


2 Answers

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

like image 68
Luis González Avatar answered Oct 13 '22 19:10

Luis González


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.

like image 25
Saad Avatar answered Oct 13 '22 19:10

Saad