Skip to content

Commit

Permalink
add validation to the post update
Browse files Browse the repository at this point in the history
  • Loading branch information
levijackson committed Jun 25, 2021
1 parent 68a339d commit 37be2ee
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
12 changes: 7 additions & 5 deletions app/Http/Controllers/PostController.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ public function update(PostRequest $request, string $slug)
{
$post = Post::where('slug', $slug)->first();

$data = $request->validated();

if ($request->has('delete')) {
$post->delete();
$message = 'Post deleted!';
Expand All @@ -93,11 +95,11 @@ public function update(PostRequest $request, string $slug)
}

$post->title = $request->get('title');
$post->metaTitle = $request->get('metaTitle');
$post->body = $request->get('body');
$post->metaDescription = $request->get('metaDescription');
$post->slug = $request->get('slug') ?? Str::slug($post->title);
$post->user_id = $request->user()->id;
$post->title = $data['title'];
$post->metaTitle = $data['metaTitle'];
$post->body = $data['body'];
$post->metaDescription = $data['metaDescription'];
$post->slug = $data['slug'] ?? Str::slug($post->title);

$message = 'Post updated!';

Expand Down
14 changes: 12 additions & 2 deletions app/Http/Requests/PostRequest.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,21 @@ public function authorize()

public function rules()
{
return [
$rules = [
'title' => 'required|max:255',
'body' => 'required',
'slug' => 'unique:posts|regex:/^[A-Za-z0-9 ]+$/i'
'slug' => 'unique:posts|regex:/^[A-Za-z0-9 ]+$/i',
'metaTitle' => 'max:255',
'metaDescription' => 'max:255'
];

if ($this->method() === 'PUT') {
// this ensures that an existing post still requires a slug, but that
// it doesn't validate against itself and trigger an error!
$rules['slug'] = 'unique:posts,title,' . $this->get('slug') . '|regex:/^[A-Za-z0-9\- ]+$/i';
}

return $rules;
}

public function messages()
Expand Down
10 changes: 10 additions & 0 deletions resources/views/blog/posts/edit.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@
</div>
@endif

@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif

<form action="/admin/blog/post/{{ $post->slug }}" method="post" class="container">
<input type="hidden" name="_method" value="PUT">

Expand Down

0 comments on commit 37be2ee

Please sign in to comment.