It seems like you're trying to apply unique validation in Laravel and want to exclude the current record from the validation check when updating. The issue you're facing with $this->id returning null could be because the id property is not being set on your form request or you might be using the wrong property to access the id of the resource being updated.
Here's a revised version of your rules method that should work for both creating and updating records:
public function rules(): array
{
$rules = [
'name' => [
'required',
'string',
'max:255',
Rule::unique('tables')->where(function ($query) {
return $query->where('user_id', auth()->id());
}),
],
];
// When updating, exclude the current record from the unique check
if ($this->isMethod('put') || $this->isMethod('patch')) {
// Assuming that this is a form request and you have a route parameter named 'table'
// which corresponds to the id of the record being updated.
$tableId = $this->route('table');
$rules['name'][] = Rule::unique('tables')->ignore($tableId);
}
return $rules;
}
In this solution, I've added a check to see if the request method is PUT or PATCH, which are typically used for updating resources. If it is an update request, we add an additional rule to ignore the current record's ID in the unique check.
Please note that $this->route('table') is used to retrieve the route parameter that should correspond to the ID of the record you're updating. Make sure that the route parameter name matches the one you have defined in your routes file.
For example, if your route is defined like this:
Route::put('/tables/{table}', 'TableController@update');
Then table is the route parameter name, and $this->route('table') will retrieve the ID of the table being updated.
Make sure to import the Rule facade at the top of your file:
use Illuminate\Validation\Rule;
This should resolve the issue with $this->id being null and apply the correct unique validation rule when updating records.