LoginSignup
0

Laravel で MariaDB の CRUD (その 6 Delete)

Last updated at Posted at 2018-06-14

こちらのページの続きです。

Laravel で MariaDB の CRUD (その 5)
データ削除機能を作ります。

  1. ルーティングを確認
  2. >articles.destroy があることを確認
    php artisan route:list
    
  3. 一覧ページに削除のリンクをつけます。
  4. resources/views/articles/index.blade.php
    {{-- layoutsフォルダのapplication.blade.phpを継承 --}}
    @extends('layouts.application')
    
    {{-- @yield('title')にテンプレートごとにtitleタグの値を代入 --}}
    @section('title', '記事一覧')
    
    {{-- application.blade.phpの@yield('content')に以下のレイアウトを代入 --}}
    @section('content')
    <div>
        <a href="/articles/create">新規作成</a>
    </div>
    <table>
     @foreach ($articles as $article)
    	<tr>
        <td>{{$article->title}}</td>
        <td>{{$article->body}}</td>
    	<td><a href="/articles/{{$article->id}}">詳細を表示</a></td>
    	<td><a href="/articles/{{$article->id}}/edit">編集する</a></td>
    <td>
    	<form action="/articles/{{$article->id}}" method="post">
          {{ csrf_field() }}
          <input type="hidden" name="_method" value="delete">
          <input type="submit" name="" value="削除する">
        </form>
        {{-- <a href="/articles/{{$article->id}}">削除する</a> --}}
    </td>
    	</tr>
      @endforeach
    </table>
    @endsection
    
  5. 詳細ページに削除のリンクをつけます。
  6. resources/views/articles/show.blade.php
    {{-- layoutsフォルダのapplication.blade.phpを継承 --}}
    @extends('layouts.application')
    
    {{-- @yield('title')にテンプレートごとの値を代入 --}}
    @section('title', '記事詳細')
    
    {{-- application.blade.phpの@yield('content')に以下のレイアウトを代入 --}}
    @section('content')
      <h1>{{$article->title}}</h1>
      <p>{{$article->body}}</p>
      <br><br>
      <a href="/articles/{{$article->id}}/edit">編集する</a>
    <form action="/articles/{{$article->id}}" method="post">
          {{ csrf_field() }}
          <input type="hidden" name="_method" value="delete">
          <input type="submit" name="" value="削除する">
        </form>
      <a href="/articles">一覧に戻る</a>
    @endsection
    
  7. destroyアクションを編集
  8. app/Http/Controllers/ArticlesController.php
    // 略
        public function destroy($id)
        {
      // idを元にレコードを検索
      $article = Article::find($id);
      // 削除
      $article->delete();
      // 一覧にリダイレクト
      return redirect('/articles');
        }
    // 略
    
  9. サーバーを起動してブラウザーで確認
  10. php artisan serve
    

    http://localhost:8000/articles
    laravel_jun1412.png
    詳細画面
    laravel_jun1413.png

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0