I'm developing a small application in Laravel 5.5
where I'm creating a request with updateContact
and having unique email validation rule, while using the same validation inside the controller I can easily make:
$contact = Contact::find($request->id);
Validator::make($data, [
'first_name' => 'required|max:255',
'email' => 'required', Rule::unique('contacts')->ignore($contact->id),
'address' => 'max:255',
'city' => 'max:255',
'state' => 'max:255',
'country' => 'max:255',
]);
and can validate, by I made out request through php artisan make:request UpdateContact
and added the following inside updateContact.php
:
namespace App\Http\Requests;
use App\Contact;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class UpdateContact 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()
{
$contact = Contact::find($request->id);
return [
'first_name' => 'required|max:255',
'email' => 'required', Rule::unique('contacts')->ignore($contact->id),
'company_id' => 'required',
'address' => 'max:255',
'city' => 'max:255',
'state' => 'max:255',
'country' => 'max:255',
];
}
public function messages()
{
return [
'company_id.required' => 'Company name is required'
];
}
}
But I don't know about the $request->id
how can I use this?
Inside a FormRequest class, $this is the variable scope of the request object. Simply do the following to get the ID property
$contact = Contact::find($this->id);
Same goes for any other field in your form.