コントローラー
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
class PostController extends Controller
{
public function create(){
return view('post.create');
}
public function store(Request $request){
$validated = $request->validate([
'title' => 'required|max:20',
'body' => 'required|max:400',
]);
$post = Post::create($validated);
/*
saveを使う場合
$post = new Post();
$post->title = $validated['title'];
$post->body = $validated['body'];
$post->save();
*/
/*
withを使わない場合
$request->session()->flash('message','保存しました');
return back();
*/
return back()->with('message','保存しました');
}
}
表示側
<div class="max-w-7xl">
@if(session('message'))
<div class="text-red-600">
{{ session('message') }}
</div>
@endif
<form method="post" action="{{ route('post.write') }}">
@csrf
<div>
<x-input-error :messages="$errors->get('title')" class="mt-2" />
<input type="text" name="title" class="w-auto py-2 border border-gray-300 rounded-md" id="title" value="{{old('title')}}">
</div>
<div>
<x-input-error :messages="$errors->get('body')" class="mt-2" />
<textarea name="body" class="w-auto py-22 border border-gray-300 rounded-md" id="body" cols="30" rows="5">{{old('body')}}</textarea>
</div>
<x-primary-button>{{ __('送信する') }}</x-primary-button>
</form>
</div>