Laravel 5使用destroy方法删除现有文章

时间:2016-09-30 11:06:53

标签: php laravel

我正在尝试使用以下代码删除文章:

ArticlesController:

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

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

查看:

@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

点击&#34;删除文章&#34;按钮我被重定向到完全不同的视图。好像@show方法已经执行了。

我的路线:

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

我该如何解决这个问题?

4 个答案:

答案 0 :(得分:4)

原因是您使用的是 标记。 使用表单标记,方法等于删除哪个可以解决您的问题。

          @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

答案 1 :(得分:2)

尝试这样做

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

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

答案 2 :(得分:2)

您需要使用delete方法来调用destroy()操作,例如:

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

您无法在此处使用a href链接。

答案 3 :(得分:0)

您没有正确传递变量。

$url = action('UserController@profile', ['id' => 1]);

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