Ad

How To Validate A Unique Field For Uniqueness Under A Category In Laravel

- 1 answer

I have two tables categories and sub_categories. I want to validate the name field of subcategories table to be unique under the same category.

sub_category table fields

id | name | category_id

Using Laravel validation I am using this code but getting error messsage ErrorException Undefined variable: request

public function update(Request $request, $id)
    {

       $validatedData = $request->validate([
          'category_id' => 'required|numeric|min:1',
          'name' => [
            'required', 'max:255',
            Rule::unique('sub_categories')->ignore($id)->where(function($query){
              return $query->where('category_id',$request->category_id);
            })
          ],

      ]);
    }
Ad

Answer

use use($request) to pass $request instance inside where condition

 public function update(Request $request, $id)
    {

        $validatedData = $request->validate([
            'category_id' => 'required|numeric|min:1',
            'name' => [
                'required', 'max:255',
                Rule::unique('sub_categories')->ignore($id)->where(function ($query) use($request) {
                    return $query->where('category_id', $request->category_id);
                }),
            ],

        ]);
    }
Ad
source: stackoverflow.com
Ad