Validate unique() only on owned models

Let's say I have a User model and a Brand model, with a one-to-many relationship between them:

User model:

public function brands()
    return $this->hasMany(\App\Brand::class);

This means different users can have different brands with the same name without conflict.

Now, I want to make a validation rule for creating brands, but ONLY for the user's owned brands, in such a way that is not possible for a user to have two brands with the same name.

How can I do this?


3 answers

  • answered 2018-11-08 08:26 Remul

    You could do something like this:

    public function rules()
        $user = \Auth::user(); // get the user
        return [
            'name' => [
                Rule::unique('brands')->where(function ($query) use ($user) {
                    $query->where('user_id', $user->id);

  • answered 2018-11-08 08:30 N69S

    if you want to do it in the model/repository part, simplu run

    $exists = (bool)$user->brands()->where('name', '=', $newBrandName)->count();

    if $exists is true, you prevent him from adding the new brand since the name is used

    if you want to do it in the validator part use the rule

    'name' => Rule::unique('brands')->where(function ($query) {
        return $query->where('user_id', auth()->id());

    be carefull for hidden dependancy.

  • answered 2018-11-08 08:35 Mou Hsiao

    What I found in Laravel Document

    Validator::make($data, [
        'name' => Rule::unique('brands')->where(function ($query) {
            return $query->where('user_id', $user_id);