記事削除まで
(#22,#23)
http://dotinstall.com/lessons/basic_laravel/36122
- 投稿リストに削除リンクをつける。
- 削除リンクをクリックしたら、フォームが送信されてdeleteメソッドが呼ばれる
/myblog/app/Http/routes.php
<?php
Route::get('/', 'PostsController@index');
Route::get('/posts/create', 'PostsController@create');
Route::get('/posts/{id}', 'PostsController@show');
Route::get('/posts/{id}/edit', 'PostsController@edit');
Route::post('/posts', 'PostsController@store');
Route::patch('/posts/{id}', 'PostsController@update');
Route::delete('/posts/{id}', 'PostsController@destroy');
Route::post('/posts/{post}/comments', 'CommentsController@store');
Route::delete('/posts/{post}/comments/{comment}', 'CommentsController@destroy');
- deleteを追加
Controller
/myblog/app/Http/Controllers/PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Post;
use App\Http\Requests\PostRequest;
class PostsController extends Controller
{
public function index() {
$posts = Post::latest('created_at')->get();
return view('posts.index')->with('posts', $posts);
}
public function show($id) {
$post = Post::findOrFail($id);
return view('posts.show')->with('post', $post);
}
public function edit($id) {
$post = Post::findOrFail($id);
return view('posts.edit')->with('post', $post);
}
public function destroy($id) {
$post = Post::findOrFail($id);
$post->delete();
return redirect('/')->with('flash_message', 'Post Deleted!');
}
public function create() {
return view('posts.create');
}
public function store(PostRequest $request) {
$post = new Post();
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect('/')->with('flash_message', 'Post Added!');
}
public function update(PostRequest $request, $id) {
$post = Post::findOrFail($id);
$post->title = $request->title;
$post->body = $request->body;
$post->save();
return redirect('/')->with('flash_message', 'Post Updated!');
}
}
- destroyメソッドを追加
/myblog/resources/views/posts/index.blade.php
@extends('layouts.default')
@section('title', 'Blog Posts')
@section('content')
<h1>
<a href="{{ url('/posts/create') }}" class="pull-right fs12">Add New</a>
Posts
</h1>
<ul>
@forelse ($posts as $post)
<li>
<a href="{{ action('PostsController@show', $post->id) }}">{{ $post->title }}</a>
<a href="{{ action('PostsController@edit', $post->id) }}" class="fs12">[Edit]</a>
//フォームの追加
<form action="{{ action('PostsController@destroy', $post->id) }}" id="form_{{ $post->id }}" method="post" style="display:inline">
{{ csrf_field() }}
{{ method_field('delete') }}
<a href="#" data-id="{{ $post->id }}" onclick="deletePost(this);" class="fs12">[x]</a>
</form>
</li>
@empty
<li>No posts yet</li>
@endforelse
</ul>
//idをsubmitする
<script>
function deletePost(e) {
'use strict';
if (confirm('are you sure?')) {
document.getElementById('form_' + e.dataset.id).submit();
}
}
</script>
@endsection
- dataに付いているidは、「e.dataset.id」で取る