muehleis's avatar

first() ignores the where clause

Hi,

when i execute

$code = Device::where('user_id', auth()->id())->where('uuid', $this->codeId)->first()->value('connect_token');

i always get the first record of my mysql-Database, so he ignores the uuid. When i remove first() it works:

$code = Device::where('user_id', auth()->id())->where('uuid', $this->codeId)->value('connect_token');

Can anyone tell me what i'm doing wrong?

0 likes
4 replies
enoch91's avatar

@muehleis Confirm that there are records in your Device table that meet both conditions specified in the where clause (user_id and uuid). Executing the query without the first() method and checking if it returns any results

jaseofspades88's avatar

It will make it easier for people to help you if you embrace markdown and wrap your code in backticks to syntax highlight.

If the data exists in your database as @enoch91 alludes to, then try grouping your clauses like so.. (notice the markdown example below)

$device = Device::query()
	->where([
		['user_id', auth()->id()],
		['uuid', $this->codeId],
	])
	->first();

$token = $device->connect_token;// do with as you wish
Snapey's avatar
Snapey
Best Answer
Level 122

The mistake is that value() runs a query.

So, first() runs a query and returns a model.

You then do $model->value() which runs a second query using the model as the basis for the query.

Your solution is to use one method or the other, not both.

$code = Device::where('user_id', auth()->id())
            ->where('uuid', $this->codeId)
            ->value('connect_token');

or

$code = Device::where('user_id', auth()->id())
            ->where('uuid', $this->codeId)
            ->first()
            ->connect_token;
2 likes
muehleis's avatar

Thank you all for your valuable Help!

Please or to participate in this conversation.