Laravel force unique role validation fail in form request

1.2k Views Asked by At

My controller is as below:

public function update(PermissionFormRequest $request,$id)
{
    $permissionUpdated = $this->permission->update($request,$id);
    if($permissionUpdated){
        //return $permissionUpdated;
        return 'updated';
    }
    return response()->json(['message' => 'Can not update ticket']);    
}

Form request code is:

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

When trying to update with same id, an error is thrown as:

{"name":["The name has already been taken."]}

2

There are 2 best solutions below

0
On BEST ANSWER

To get the id in the Request you can use the route() method. Keep in mind that use parameter name in route('id') which is used in your routes.php file!

public function rules()
{
    $id = $this->route('id'); //or whatever it is named in the route
    return [
        'name' =>'required|unique:permissions,name,'.$id,
    ];
}

Hope this helps!

0
On

In form request you can get id by two way one is segment and another is route() function.

If you are using resource controller like

Route::resource('permissions','PermissionController'); then $this->route('permission');

or

you are using custom route like /permissions/{id} then $this->route('id');

public function rules()
{
    $id = $this->route('permission');
    return [
        'name' =>'required|unique:permissions,name,'.$id,
    ];
}

Or we can use segment also for getting id from route

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