简体   繁体   中英

Laravel Eloquent delete by id

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.

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

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

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

**Step 1 create route inside web.php**

Route::delete('/answers_delete/{id}', [App\Http\Controllers\AnswerController::class, 'delete'])->name('answers.delete');

 **Step 2 Create method in your controller**
use App\Models\Answer; // use in top of this file
public function delete($id)
    {
        $ans = Answer::find($id);
        $ans->delete();
        session()->flash('success', 'Answer Deleted Successfully!!!');
        return view('admin.anser.index');
    }

**Step 3 define your route name inside form action(Note my case view file name index.blade.php and inside admin/answer/index.blade.php)*

<form action="{{ route('answers.delete', $answer->id) }}" method="POST">
  @csrf
  @method('DELETE')
<button type="submit" class="btn btn-danger" style="display: inline;">Delete</button>
</form>

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