1 year ago

Validate unique slug

Posted 1 year ago by jorgeyoma


I've been struggling with this and I can't find a solution.

I use slugs for everything that may be included on the url. So I have slugs in posts, tags, categories, products and services.

I do not want to bother my customer with the "slug" term, so I create the slug internally and check it against the title or name on the Controller with a validator.

I know this is a awful code and I have to copy it in all my Controllers. Any idea on how to implement a rule in a more modular and straightforward way?

In this case I have to return the error to the title so it can be shown as I don't have a slug field in the form.

  • Form Request doesn't apply as I want a solution than can be used with several Models.
  • Rules Objects only check the value, cant be used for unique field.
  • maybe a Rule:: statement but I cant find much information about it to develop the solution.

    public function store(Request $request){


      $validator = Validator::make($request->all(),[
        'title'   =>  'required|min:10|max:100',
        'body'    =>  'required|min:50',
        'slug'    =>  'unique:posts,slug'


        $errors = $validator->errors();

          return response()->json(
            [ 'message'=>'Error por slug repetido',
              'errors' => ['title' => ['El titulo del Post esta repetido']]
            ], 422);



Please sign in or create an account to participate in this conversation.