Skip to content

Commit

Permalink
adding PostRequest and displaying errors
Browse files Browse the repository at this point in the history
  • Loading branch information
levijackson committed Jun 25, 2021
1 parent c5d1b86 commit a1a6bbf
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 7 deletions.
18 changes: 11 additions & 7 deletions app/Http/Controllers/PostController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@

use App\Models\Post;

use App\Http\Requests\PostRequest;

class PostController extends Controller
{
public function index()
Expand Down Expand Up @@ -41,14 +43,16 @@ public function single(Request $request, string $slug)
->withErrors('This post does not exist.');
}

public function save(Request $request)
public function save(PostRequest $request)
{
$data = $request->validated();

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

if ($request->has('draft')) {
Expand Down Expand Up @@ -77,7 +81,7 @@ public function edit(Request $request, string $slug)
->withErrors('You do not have permission to edit this post.');
}

public function update(Request $request, string $slug)
public function update(PostRequest $request, string $slug)
{
$post = Post::where('slug', $slug)->first();

Expand Down
32 changes: 32 additions & 0 deletions app/Http/Requests/PostRequest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class PostRequest extends FormRequest
{
public function authorize()
{
if ($this->user()->canManagePosts()) {
return true;
}
return false;
}

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

public function messages()
{
return [
'title.required' => 'Please add a title',
'body.required' => 'Please add some content to the post'
];
}
}
10 changes: 10 additions & 0 deletions resources/views/blog/posts/create.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" method="post" class="container">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
Expand Down

0 comments on commit a1a6bbf

Please sign in to comment.