一、驗證
建立 request
php artisan make:request PostRequest
修改 request(app/Http/Requests/PostRequest)
class PostRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required',
'content' => 'required',
];
}
}
修改 controller
use App\Http\Requests\PostRequest;
...
public function store(PostRequest $request)
{
$post = new Post();
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect()->route('post.index');
}
public function update(PostRequest $request, Post $post)
{
$post->title = $request->title;
$post->content = $request->content;
$post->save();
return redirect()->route('post.index');
}
修改 view(create、edit)
@if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
二、fillable
修改 model
class Post extends Model
{
protected $fillable = ['title', 'content'];
}
修改 controller
public function store(PostRequest $request)
{
Post::create($request->all());
return redirect()->route('post.index');
}
public function update(PostRequest $request, Post $post)
{
$post->update($request->all());
return redirect()->route('post.index');
}
留言
張貼留言