jeudi 23 mai 2019

Returning an empty JSON object when a nullable column value is null within an eloquent query scope

I have the following query scope that will return keys (JSON) that may be stored inside a container:

public function scopeKeys($query, $container)
{
    return $query->select('keys')
        ->whereNotNull('keys')
        ->where('name', $container)
        ->value('keys');
}

...in my controller I access this via:

Containers::keys($container);

When the keys exists, I get them back as expected; however; when the keys field is null, I get the following error:

Object of class Illuminate\Database\Eloquent\Builder could not be converted to string

I'd like to avoid using firstOrFail() as I don't want to throw a 404, I want to return an empty JSON object.

I'm sure I could utilize ->exists() to check then conditionally return but then I'm making two queries if they do exist - seems sloppy.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire