PostRequest Classを作る

なるほど、classを作る際はphp artisan make:hogeね。
[vagrant@localhost myblog]$ php artisan make:request PostRequest
Request created successfully.

post request classが出来た。

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|min:3',
            'body' => 'required',
        ];
    }

    public function messages(){
        return [
            'title.required' => 'please enter title!!!'
        ];
    }    
}

PostsController.phpも変更する。

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Http\Requests\PostRequest;

class PostsController extends Controller
{
    //
    public function index(){
    	// $posts = Post::orderBy('created_at', 'desc')->get();
    	$posts = Post::latest()->get();
    	// $posts = [];
    	// dd($posts->toArray()); // dump die
    	// return view('posts.index', ['posts' => $posts]);
    	return view('posts.index')->with('posts', $posts);
    }

    public function show(Post $post){
    	// $post = Post::find($id);
    	// $posts = Post::findOrFail($id);
		return view('posts.show')->with('post', $post);
    }

    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('/');
    }

    public function edit(Post $post){
		return view('posts.edit')->with('post', $post);
    }

    public function update(PostRequest $request, Post $post){
    	$post->title = $request->title;
    	$post->body = $request->body;
    	$post->save();
    	return redirect('/');
    }
}