Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating a Unique Slug on Update in Laravel 5

I currently have a model that has a text field and a slug field.

I validate that the slug is unique in my form request class:

public function rules()
{
    return [
        'name' => 'required|min:3',
        'slug' => 'required|alpha_dash|unique:questions'
    ];
}

This works fine on create and properly denies the creation of duplicate slugs. However on my update method, it won't let me save a record because the slug already exists. Of course the slug does exist, but it exists on the record being edited, so I would like to continue to allow it to be saved. However, it should not be able to be changed to a slug on ANOTHER record.

Here's what my update ArticlesController method looks like:

public function update(Article $article, ArticleRequest $request)
{
    $article->update($request->all());

    return redirect('articles');
}

Is there a way to make this work in L5?

like image 976
Rapture Avatar asked Feb 22 '15 19:02

Rapture


People also ask

How validate unique email out of the user that is updating it in laravel?

Sometime we need to add unique validation on update for email, username etc. at that time if you check unique email or username then you have to write database query manually and do it using if condition. but laravel provide "unique" rule that will help to easily add unique validation.

Is unique validation in laravel?

Laravel includes a wide variety of convenient validation rules that you may apply to data, even providing the ability to validate if values are unique in a given database table.

How do I validate a timestamp in laravel?

Just create a new validation rule in laravel to validate the timestamp... Validator::extend('isTimeStamp', function($attribute, $value, $parameters) { return ((string) (int) $value === $value) && ($value <= PHP_INT_MAX) && ($value >= ~PHP_INT_MAX); }); You can now use isTimeStamp validation rule to validate timestamp.


2 Answers

Try to modify your rule like following(in form request class):

public function rules()
{
    return [
      'name'  => 'required,min:3',
      'slug'  => 'required|alpha_dash|unique:categories,slug,'.$this->id')
    ];
}

It works for me.

like image 132
Purple Avatar answered Sep 19 '22 02:09

Purple


In unique rule you may specify id you want to ignore.

You can create 2 separate request (one for create and one for update), but you can do it also this way checking if if is set(I assume your update url looks like /questions/2 ):

public function rules()
{
    $rules = [
        'name' => 'required|min:3',
        'slug' => ['required', 'alpha_dash']
    ];

    $rule = 'unique:questions';

    $segments = $this->segments();
    $id = intval(end($segments));
    if ($id != 0) {  
         $rule .= ',slug,' . $id;
    }
    $rules['slug'][] = $rule;

    return $rules;
    }
}
like image 28
Marcin Nabiałek Avatar answered Sep 19 '22 02:09

Marcin Nabiałek