I have this form request as follows:
<?php
namespace App\Http\Requests;
use App\Sociallink;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class SociallinkRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'seq' => 'required|unique:sociallinks,seq,' . $this->id . ',id',
'social_name' => 'required|unique:sociallinks,social_name,' . $this->id . ',id',
'cssclass' => 'required',
'url' => 'nullable|active_url'
];
}
I need the fields seq
and social_name
as unique. When I am trying to edit, this code is not working. I found that $this->id
doesnt exist from dd($this)
. My URL is: http://prj.test/sociallink/2/edit
. Many examples here make use of $this->id
but I cant access the variable anywhere in my code as it seems to be non existent. When I replace $this->id
with a physical id
like 2
in this example then the validation works fine. But dynamically, how do I use the current row's id
to do the unique validation?
Unless you have a form input with the id
, it is not actually in the $request
($this
in your Request code). You can verify this by returning the whole request from your controller:
return request()->all();
Assuming you have this route defined something like:
sociallink/{sociallink}/edit ...
Then in your Request you can do:
public function rules()
{
$sociallink = $this->route('sociallink');
return [
'seq' => 'required|unique:sociallinks,seq,' . $sociallink . ',id',
'social_name' => 'required|unique:sociallinks,social_name,' . $sociallink . ',id',
'cssclass' => 'required',
'url' => 'nullable|active_url'
];
}
There is an example of this in the Form Request documentation:
Also note the call to the
route
method in the example above. This method grants you access to the URI parameters defined on the route being called, such as the{comment}
parameter in the example below:
Route::post('comment/{comment}');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With