Checking record existence in Laravel: correct ways and common mistakes
Hello everyone! I'm new to Laravel and PHP, writing my first project — a simple blog. I have a Post model and a posts table. I need to check before adding a new post whether a record with the same title (slug) already exists. I've tried several options, but I feel like I'm doing something wrong.
Here's my current code in the controller:
\n\npublic function store(Request $request)\n{\n $slug = $request->input('slug');\n $existing = DB::table('posts')->where('slug', $slug)->get();\n if (count($existing) > 0) {\n return back()->with('error', 'Such slug already exists');\n }\n // ... saving\n}\n\nBut I've read that using count() and get() for this is inefficient, especially
No answers yet.
Log in to leave an answer
Blogs
CI/CD for C# (.NET) Projects with GitHub Actions: A Step-by-Step Guide