Mamulasa Mamulasa - 2 months ago 15
PHP Question

Laravel 5 Delete existing Article with destroy method

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?

Answer

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