Avatar ·

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.

\n\n

Here's my current code in the controller:

\n\n
public 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\n

But I've read that using count() and get() for this is inefficient, especially