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

bellini's avatar

Where clause to validation request

Hey, in the documentation i found the example of how to add a where clause to a validation, like this:

'email' => Rule::unique('users')->where(function ($query) {
    return $query->where('account_id', 1);
})

but i am using a request i created using the rules method like this:

public function rules()
    {
        return [
                'coin' => 'unique:trackers',
        ];
    }

how would the syntax be here? i need to make 'coin' unique where the 'user_id' is equal to the current id auth()->id()

0 likes
3 replies
Vilfago's avatar

Just the same :

public function rules()
{
    return [
        'coin' => Rule::unique('trackers')->where(function ($query) {
            return $query->where('account_id', 1);
        })
    ];
}
1 like
bellini's avatar

@VILFAGO -

public function rules()
{
    $userId = auth()->id();
    return [
        'coin' => Rule::unique('trackers')->where(function ($query) {
            return $query->where('user_id', $userId);
        })
    ];
}

something like this. Thank you.

Vilfago's avatar
public function rules()
{
    $userId = auth()->id();
    return [
        'coin' => Rule::unique('trackers')->where(function ($query) use($userId) {
            return $query->where('user_id', $userId);
        })
    ];
}
1 like

Please or to participate in this conversation.