The error you're encountering is due to the fact that the value you're passing to the where clause is not a valid UUID format, and PostgreSQL is strict about UUID formats. When you pass an invalid UUID, it throws an error instead of returning NULL.
To handle this situation, you can validate the UUID format before querying the database. If the UUID is invalid, you can return NULL directly without making a database query. Here's how you can do it:
- Use PHP's
filter_varfunction with theFILTER_VALIDATE_REGEXPfilter to validate the UUID format. - If the UUID is valid, proceed with the query. Otherwise, return
NULL.
Here's how you can implement this in your controller:
use Illuminate\Support\Facades\Validator;
public function getPostByUuid($value)
{
// Define a regex pattern for UUID validation
$uuidPattern = '/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/';
// Validate the UUID format
if (!preg_match($uuidPattern, $value)) {
// Return NULL if the UUID is not valid
return null;
}
// Proceed with the query if the UUID is valid
$post = Posts::where('uuid_key', $value)->first();
return $post;
}
This approach ensures that you only query the database with valid UUIDs, thus avoiding the SQL error you're encountering. If the UUID is invalid, it simply returns NULL without attempting a database query.