murilo's avatar
Level 10

error model with uuid_key in postgres when not found

hello , I am using uuid_key and Postgres with Laravel I have a problem here , if dont find the uuid_key at the model , it showld return NULL , but it is giving an error .

at my model -

class Posts extends Model
{
    use UuidSet;

    protected $fillable = [
        'id' ,
        'uuid_key',
        'title' ,
        'description' 
    ];

at controller -

$post = Posts::where('uuid_key', $value )->first();
dd($post);

if the uuid_key exists , it will give the Post . but if is not , it showld give NULL as result . but it is giving an error -

SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type uuid: \"123\"\nCONTEXT:  unnamed portal parameter $1 = '...' (Connection: pgsql, SQL: select count(*) as aggregate from \"posts\" where \"uuid_key\" = 123 and .....
0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

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:

  1. Use PHP's filter_var function with the FILTER_VALIDATE_REGEXP filter to validate the UUID format.
  2. 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.

Please or to participate in this conversation.