Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

hiaaryan's avatar

Crypt in Eloquent Query

Hello, so I am defining a relationship with a user and the core database where all entries are encrypted. For this I have assigned an encrypted key to each user so that using the eloquent query I can find out which row belongs to which user.

$get = Model::firstWhere('key', Crypt::decrypt(Auth::user()->key));

The 'key' is also encrypted in the core db.

I am using the encryptable trait which automatically decrypts the key on call. But however for some reason it is not decrypting it in the eloquent query. Obviously, now there's something wrong with my code here. Is there a way out of this or any alternative?

0 likes
10 replies
MichalOravec's avatar

If it's encrypted everywhere it should be like this

$get = Model::firstWhere('key', Auth::user()->key);
hiaaryan's avatar

Hey, thanks for the reply

However, it's the 'key' ie the first parameter in the query I want to decrypt to match the results. It doesn't get decrypted in the eloquent query I guess?

Thanks :)

MichalOravec's avatar

In Model key is encrypted, in User it's also encrypted, but you use trait where when you call it it will be automatically decrypts. So you have to encrypt it again.

$get = Model::firstWhere('key', encrypt(Auth::user()->key));
hiaaryan's avatar

Well, the question is,

I want to do this

$get = Model::firstWhere(Crypt::decrypt('key'), Crypt::decrypt(Auth::user()->key));

& it will get me the row which has the same key when decrypted.

But I cannot do that because Crypt::decrypt('key') is not a valid parameter and it will not search the column. The Crypt Facade will give me a "Low Payload" error.

Since laravel encryptions are randomized and it is not suggested to use the same encrypted string two places.

MichalOravec's avatar

But it doesn't matter if you compare encrypted or decrypted key, if you compare every time the same value.

And another question why you don't use forein key?

hiaaryan's avatar
hiaaryan
OP
Best Answer
Level 1

Oh thanks btw, I found a way out of this.

I used a raw randomized key in the core db and an encrypted key in the user db. It matches perfectly.

Thanks :)

hiaaryan's avatar

$get = Model::firstWhere('key', Crypt::decrypt(Auth::user()->key));

MichalOravec's avatar

@myselfaaryan And what is different from your original post?

You had there the same

$get = Model::firstWhere('key', Crypt::decrypt(Auth::user()->key));

Please or to participate in this conversation.