てくてくあるく

WordPress の テーマ とか プラグイン に ついて 勉強しています

前回は データの編集を 行ったので
今回は データの削除を 行いたいと思います

今回の削除方法は 物理削除 ( DBから削除する ) になります


ビューの編集


インデックスページ ( resources / views / links / index.blade.php ) から 削除ボタンを押すと 削除する ように 直接フォームを 埋め込みます

@extends('links.default')

@section('title', 'links.index')

@section('style')
      .links dd {
        margin-left: 2rem;
        word-break: break-all;
      }
@endsection

@section('content')
      <section class="my-3 links">
        <header>
          <h2 class="text-center">@yield('title')</h2>
        </header>
        <div class="d-grid gap-2 d-md-flex justify-content-md-end">
          <a class="btn btn-primary" href="{{ url("/links/create") }}">Add</a>
        </div>
        <dl>
          @foreach ($links as $link)
            <dt><a href="{{ $link->url }}">{{ $link->title }}</a></dt>
            <dd>{{ $link->description }}</dd>
            <dd>
              <a class="btn btn-success" href="{{ url("/links/{$link->id}/edit") }}">Edit</a>
              <form class="d-inline-block" action="{{ route('links.destroy', $link->id) }}" method="post">
                @csrf
                @method('DELETE')
                <button class="btn btn-danger">Delete</button>
              </form>
            </dd>
          @endforeach
        </dl>
      </section>
@endsection

コントローラの編集


前回編集した app / Http / Controllers / LinkController.phppublic function destroy() の 中身を書き換えます

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Link::where('id', $id)->delete();

        return redirect('/links')->with('success', 'deleted successfully !');
    }

ルーティングの設定


ルーティング は routes / web.php で 設定します

今回は app / Http / Controllers / LinkController.phpdestroy を 追加します

Route::resource('/links', App\Http\Controllers\LinkController::class)->only(['index','create','store','edit','update','destroy']);

ページの確認


http://localhost:50000/links/ から 確認します

  • リンク一覧に Deleteボタンが追加されている
  • Deleteボタンを押したら リンクが消える

等が 確認できれば 完成です

Related Article

[ はじめて の Laravel ] リンク一覧ページ を 作る No.1

詳細へ »

[ はじめて の Laravel ] リンク一覧ページ を 作る No.4

詳細へ »

[ はじめて の Laravel ] リンク一覧ページ を 作る No.7 – フラッシュメッセージ

詳細へ »