I have created a PostRequest in Laravel (using php artisan make:request PostRequest
). I have three columns: title, content, and tag). The tag column is nullable. When I add some posts there is no problem, I am able to add title, content, and tag.
However, when I want to edit a post, the title and content column change but the tag column is not. How can handle this?
Controller
public function update(PostRequest $request, Post $post)
{
$validated = $request->validated();
Post::whereId($post->id)->update($validated);
return redirect('/posts')->with('success', 'success');
}
PostRequest.php
public function rules()
{
switch ($this->method()) {
case 'POST':
{
return [
'title' => 'required|max:512',
'content' => 'required',
];
}
case 'PUT':
case 'PATCH':
{
return [
'title' => 'required|max:512',
'content' => 'required',
];
}
default:
break;
}
}
Post.php (model)
protected $fillable = [
'title',
'content',
'tag',
'created_at',
];
You are using $request->validated()
that filters your request inputs and returns only validated fields. So adding a new rule for tag
will fix your issue:
return [
'title' => 'required|max:512',
'content' => 'required',
'tag' => 'nullable'
];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.