1. In controller , function store:
public function store(Request $request)
{
$slug = Str::slug($request->input('title'));
$validated = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'content' => 'nullable|string',
'tags' => 'nullable|array',
'status' => 'required|in:draft,published',
]);
// Check if slug already exists
if (KnowledgeBase::where('slug', $slug)->exists()) {
return back()
->withInput()
->withErrors(['title' => 'A record with this title already exists. Please choose a different title.']);
}
$validated['slug'] = $slug;
$validated['author_id'] = auth()->id();
KnowledgeBase::create($validated);
return redirect()->route('knowledge_base.index')->with('success', 'Entry created successfully!');
}
2.In controller function update:
public function update(Request $request, KnowledgeBase $knowledgeBase)
{
$slug = Str::slug($request->input('title'));
$validated = $request->validate([
'title' => 'required|string|max:255',
'description' => 'nullable|string',
'content' => 'nullable|string',
'tags' => 'nullable|array',
'status' => 'required|in:draft,published',
]);
// Check if slug already exists (excluding the current record)
if (KnowledgeBase::where('slug', $slug)->where('id', '!=', $knowledgeBase->id)->exists()) {
return back()
->withInput()
->withErrors(['title' => 'A record with this title already exists. Please choose a different title.']);
}
$validated['slug'] = $slug;
$knowledgeBase->update($validated);
return redirect()->route('knowledge_base.index')->with('success', 'Entry updated successfully!');
}
3. In create.blade on form action add or change input field:
<form action="{{ route('knowledge_base.store') }}" method="POST">
@csrf
<div class="mb-4">
<label for="title" class="block text-sm font-medium text-gray-700">{{ __('Title') }}</label>
<input
type="text"
name="title"
id="title"
value="{{ old('title') }}"
class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500 sm:text-sm @error('title') border-red-500 @enderror"
required
autofocus
>
@error('title')
<p class="text-red-500 text-xs mt-1">{{ $message }}</p>
@enderror
</div>
<!-- Other form fields... -->