Hey there, in my comment system I have the comments form and replies form, whenever someone comments and posts empty, over character limit etc they'll get an error, my only issue is that the error also appears in my reply content because they have the same name @error('content'), does anyone know a fix or a way around this? Thanks
#Validating Error System
16 messages · Page 1 of 1 (latest)
show code
<?php
namespace App\Http\Controllers;
use App\Models\Comment;
use App\Models\CommentReply;
use Illuminate\Http\Request;
class CommentController extends Controller
{
public function storeComment(Request $request)
{
$request->validate([
'content' => 'required|max:500',
'post_id' => 'required|exists:posts,id',
], [
'content.required' => 'Comment content is required.',
'content.max' => 'Max characters allowed for a comment is 500.',
'post_id.required' => 'Post ID is required.',
'post_id.exists' => 'The selected post does not exist.',
]);
try {
$comment = new Comment();
$comment->user_id = auth()->id();
$comment->post_id = $request->post_id;
$comment->content = $request->content;
$comment->save();
return redirect()->back()->with('success', 'Comment posted successfully!');
} catch (\Exception $e) {
return redirect()->back()->with('error', 'Max characters allowed for a comment is 500!');
}
}
public function storeReply(Request $request)
{
$request->validate([
'content' => 'required|max:500',
'comment_id' => 'required|exists:comments,id',
],[
'content.required' => 'Reply content is required.',
'content.max' => 'Max characters allowed for a reply is 500.',
'comment_id.required' => 'Comment ID is required.',
'comment_id.exists' => 'The selected comment does not exist.',
]);
$reply = new CommentReply();
$reply->user_id = auth()->id();
$reply->comment_id = $request->comment_id;
$reply->content = $request->content;
$reply->save();
return redirect()->back()->with('success', 'Reply posted successfully!');
}
}
1st off your whole try-catch block is unnecessary because $request->validate() will throw a ValidationException
Yeah, was trying something forgot to remove mb
2nd you should save the comment like so so as to not waste lines of code:
$validated = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
Post::create($validated);
Ah, alright
thanks for that
any way so they don't conflict with one another when giving error messages tho?
Because I call both @error('content')
yep
$validatedData = $request->validateWithBag('post', [
'title' => ['required', 'unique:posts', 'max:255'],
'body' => ['required'],
]);
would return errors with keys like post.title and post.body
<input ... class="@error('title', 'post') is-invalid @enderror">
The docs are a little broken up but if you just search on the validation page "named error bags" you can find the relevant info