简体   繁体   中英

How to add a custom validation rule in Laravel?

I would like to add custom validations rules on my Laravel Controller:

  • The container exists in the database
  • The logged user is owner of the resource

So I wrote this:

public function update($id, Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|unique:stock.containers|max:255'
    ]);

    $container = Container::find($id);

    if(!$container)
    {
        $validator->errors()->add('id', 'Not a valid resource');
    }

    if($container->owner_id != user_id())
    {
        $validator->errors()->add('owner_id', 'Not owner of this resource');
    }

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);  //i'm not getting any
    }
}

Unfortunately the $validator->errors() or even $validator->addMessageBag() does not work. I noticed $validator->fails() clears the error messages and adding an error will not make the validation to fail.

What is the proper way to achieve this?

Then you can use after :

public function update($id, Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|unique:stock.containers|max:255'
    ]);

    $validator->after(function($validator) use($id) {
        $container = Container::find($id);

        if(!$container)
        {
            $validator->errors()->add('id', 'Not a valid resource');
        }

        if($container->owner_id != user_id())
        {
            $validator->errors()->add('owner_id', 'Not owner of this resource');
        }
    });

    if ($validator->fails()) {
        return response()->json($validator->errors(), 422);  //i'm not getting any
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM