1

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);
            })
          ],

      ]);
    }
Kamlesh Paul
  • 11,778
  • 2
  • 20
  • 33
GAURAV PAWAR
  • 33
  • 1
  • 9
  • Does this answer your question? [ErrorException: Undefined variable: request in file](https://stackoverflow.com/questions/59890456/errorexception-undefined-variable-request-in-file) – Bhaumik Pandhi Jan 30 '20 at 12:02

2 Answers2

2

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);
                }),
            ],

        ]);
    }
Kamlesh Paul
  • 11,778
  • 2
  • 20
  • 33
  • I don't want unique validation to fail if the name is under different category...ie if sub_category have same name but different category_id – GAURAV PAWAR Jan 30 '20 at 12:42
-1
public function update(Request $request, $id){
        request()->validate([
            'category_id' => 'required|numeric|min:1',
            'name'=> 'required|Max:255|unique:sub_categories,name,'. $id.',id'
        ]);
    }
mamaye
  • 1,009
  • 1
  • 8
  • 17
  • Please don't post only code as an answer, but include an explanation what your code does and how it answers the question. Answers with an explanation are generally of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Jan 30 '20 at 18:06