Home » Php » php – Laravel 5 Delete existing Article with destroy method

php – Laravel 5 Delete existing Article with destroy method

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am trying to delete an article with the following code:

ArticlesController:

public function destroy($id) {
  $article = Article::findOrFail($id);
  $article->delete();

  return redirect('backend/dashboard')->with([
    'flash_message' => 'Deleted',
    'flash_message_important' => false
  ]);
}

View:

@foreach($articles as $key => $article)
  <tr>
    <td class="td-actions text-right">
      <a  href="{{action('[email protected]',$article->id)}}"type="button" rel="tooltip" title="" class="btn btn-info btn-simple btn-xs" data-original-title="Edit Article">
        <i class="fa fa-edit"></i>
      </a>
      <a href="{{action('[email protected]',$article->id)}}" type="button" rel="tooltip" title="" class="btn btn-danger btn-simple btn-xs" data-original-title="Delete Article">
        <i class="fa fa-times"></i>
      </a>
    </td>
  </tr>
@endforech

By clicking the “Delete Article” Button I am redirected to a total different view. It seems like the @show method is executed.

My Routes:

Route::get('backend/articles/archive', '[email protected]');
Route::resource('backend/articles', 'ArticlesController');
Route::get('backend/dashboard', [
  'middleware' => 'auth',
  'uses' => '[email protected]'
]);

How can I fix this?

How to&Answers:

The reason is because you are using a tag.
Use the form tag with method equals to delete which will solve your problem.

          @foreach($articles as $key => $article)
            <tr>
             <td class="td-actions text-right">
                <a  href="{{action('[email protected]',$article->id)}}"type="button" rel="tooltip" title="" class="btn btn-info btn-simple btn-xs" data-original-title="Edit Article">
                  <i class="fa fa-edit"></i>
                </a>

                {{ Form::open([ 'method'  => 'delete', 'route' => [ 'items.destroy', $item->id ] ]) }}
                    {{ Form::submit('Delete', ['class' => 'btn btn-danger']) }}
                {{ Form::close() }}

             </td>
            </tr>
            @endforech

Answer:

Try to do like this

public function destroy($id) {
  $article = Article::findOrFail($id);
  $article->delete();

  return view('dashboard')->with([
    'flash_message' => 'Deleted',
    'flash_message_important' => false
  ]);
}

Answer:

You need to use delete method to call destroy() action, for example:

{!! Form::open(['method' => 'Delete', 'route' => ['article.destroy', $id]]) !!}
<button type="submit" class="btn">Delete article</button>
{!! Form::close() !!}

You can’t use a href link here.

Answer:

You are not passing the variables correctly.

$url = action('[email protected]', ['id' => 1]);

Source: https://laravel.com/docs/5.3/helpers#method-action