Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Delete existing Article with destroy method

Tags:

php

laravel

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('ArticlesController@edit',$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('ArticlesController@destroy',$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', 'ArticlesController@archive');
Route::resource('backend/articles', 'ArticlesController');
Route::get('backend/dashboard', [
  'middleware' => 'auth',
  'uses' => 'PagesController@dashboard'
]);

How can I fix this?

like image 338
Mamulasa Avatar asked Sep 30 '16 11:09

Mamulasa


2 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('ArticlesController@edit',$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
like image 183
Sameer Shaikh Avatar answered Oct 18 '22 18:10

Sameer Shaikh


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
  ]);
}
like image 41
Komal Avatar answered Oct 18 '22 17:10

Komal