Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent delete by id

Tags:

php

laravel

I'm trying to delete a single record by id. Instead, it deletes all records in that table.

Here's my code:

View

<form role="form" action="{{ route('status.delete', ['statusId' => $status->id]) }}" method="post">
    <button type="submit" class="btn btn-default"><i class="fa fa-times"></i> Delete</button>
    <input type="hidden" name="_token" value="{{ Session::token() }}">
</form>

Routes

Route::post('/status/{statusId}/delete', [
    'uses' => '\Dashboard\Http\Controllers\StatusController@deleteStatus',
    'as' => 'status.delete',
    'middleware' => ['auth'],
]);

Controller

public function deleteStatus(Request $request, $statusId)
{
    Auth::user()->statuses()->delete($statusId);

    return redirect()->route('home')->with('success', 'Post deleted.');
}

Note: When I dd($statusId) it does provide the right ID for the status I'm deleting. So that part does work.

like image 923
Sam Avatar asked Sep 16 '15 18:09

Sam


3 Answers

Unfortunately, the Eloquent builder does not support passing the id to delete.

Instead, you have to first find to model, then call delete on it:

$request->user()->statuses()->findOrFail($statusId)->delete();
like image 122
Joseph Silber Avatar answered Oct 11 '22 23:10

Joseph Silber


This is possible in Laravel 5.6 using the destroy method:

From the docs:

However, if you know the primary key of the model, you may delete the model without retrieving it. To do so, call the destroy method

App\Model::destroy(1);

or to delete an array of ids:

App\Model::destroy([1, 2, 3]);

or by query:

App\Model::where('active', 0)->delete();
like image 23
toing_toing Avatar answered Oct 11 '22 22:10

toing_toing


you can delete the model by using another approach like

App\Models\ModelName::find(id)->delete()

but it throws nullPointerException that you have to handle

like image 31
Danish Mehmood Avatar answered Oct 11 '22 23:10

Danish Mehmood