I'm trying to run this update function in my laravel controller. Here my domain name is an unique attribute.
The problem
But now every time when I'm trying to update any field rather than domain name field, it showing me an error saying domain name is already existing. So how can I update only the fields which have been changed? what changes do I need to be made in the following function.
public function update(Request $request,Website $app, $id)
{
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' =>['required'],
'packageType'=>['required'],
'themeid'=>['required'],
'lang'=>['required'],
'user'=>['required'],
'domain' => ['required', 'string','min:2', 'max:255','unique:apps'],
],$request->all());
$fullDomain = $request->domain;
$app->domain=$fullDomain;
Website::find($id)->update($request->all());
return redirect()->route('customers.index')
->with('success','Website updated successfully');
}
You can specify a model to be ignored on the unique attribute:
public function update(Request $request, Website $websiteModel, int $id)
{
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
$website->update($request->all());
return redirect()
->route('customers.index')
->with('success','Website updated successfully');
}
Don't forget to import Rule: use Illuminate\Validation\Rule;
Related
I am wanting to create a log that informs the registration of a new user, the problem is in the line, i'm wanting to create a log that informs the registration of a new user, the problem is in the line $log_message = Log::channel('logRegisterUser')->info("{$name_user} registered using the IP {$ip_user} in {$data}."); which when placed in a dd() is revealed as null. With this creating error at line 'description_log' => $log_message,.
logging.php
'logRegisterUser' => [
'driver' => 'single',
'path' => storage_path('logs/logRegisterUser.log'),
'level' => 'debug',
],
RegisteredUserController.php
public function __construct()
{
$this->logModel = new LoggingModel();
}
public function create()
{
return view('auth.register');
}
public function store(Request $request)
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
$date = Carbon::now()->format('d/m/Y H:i:s');
$name_user = $user->name;
$ip_user = request()->ip();
$log_message = Log::channel('logRegisterUser')->info("{$name_user} registered using the IP {$ip_user} in {$data}.");
$this->logModel->create([
'description_log' => $log_message,
'relation' => '',
]);
Auth::login($user);
return redirect(RouteServiceProvider::HOME);
}
Log->info() does not return a value. Instead write message in your variable first and then pass it to your Logger :
$log_message = "{$name_user} registered using the IP {$ip_user} in {$data}.";
Log::channel('logRegisterUser')->info($log_message);
Form
{!! Form::select('grade_level[]', $grade_level,[], array('class' => 'form-control','multiple')) !!}
Controller
Here is my create function that will return the a view and the list of roles and grade level for users
public function create()
{
$grade_level = GradeLevel::pluck('grade_level','id')->all();
$roles = Role::pluck('name','name')->all();
return view('users.create',compact('roles','grade_level'));
}
Here is the store function. and I have encounter a problem MySql Error: 1364 Field 'grade_level_id' doesn't have default value
public function store(Request $request)
{
$this->validate($request, [
'f_name' => 'required',
'm_name' => 'required',
'l_name' => 'required',
'sex' => 'required',
'id_number' => 'required',
'address' => 'required',
// 'email' => 'required|email|unique:users,email',
'username' => 'required|unique:users',
'password' => 'required|same:confirm-password',
'grade_level_id' => 'required',
'roles' => 'required'
]);
$input = $request->all();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
$user->grade_level_id = $request->grade_level;
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User created successfully');
}
I see you're using User::create() method to add new user, you'd need to add grade_level_id to the fillable property or your User model.
protected $fillable = [
'grade_level_id'
];
Find More about it here : https://laravel.com/docs/8.x/eloquent#mass-assignment
Either add 'grade_level_id' to the $fillable of your user model,
or
inside your migration, you can add the ->nullable(); extension to the grade_level_id field declaration
I'm trying to validate a unique entry in my laravel app
following is my validation array,
$website = $websiteModel->find($id);
$this->validate($request, [
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
], $request->all());
My validation working properly BUT,
When i tried to enter a duplicate value for my domain field, It get validated properly but not showing the error message, saying sorry the name is already exists...
<input type="text" id="domain" class="form-control" name="domain" >
{!! $errors->first('domain', '<span class="help-block" role="alert">:message</span>') !!}
Here in this span it shows nothing but in the common error message area it shows sorry the form cannot be updated... So how can I validate the field properly and display the relevant error message
Do something like this:
On insert request use
'domain' => [
...
'unique:websites,domain'
]
On update request use
'domain' => [
...
"unique:websites,domain,{$this->website->id}"
]
Or
'domain' => [
...
Rule::unique('websites', 'domain')->ignore($this->website)
]
You passed $request->all() as validation messages.
Please Try:
$website = $websiteModel->find($id);
$request->validate([
'subDomainName' => ['required','regex:/^[A-Za-z0-9 ]+$/'],
'subDomainSuffix' => ['required'],
'packageType' => ['required'],
'themeid' => ['required'],
'lang' => ['required'],
'user' => ['required'],
'domain' => [
'required',
'string',
'min:2',
'max:255',
Rule::unique('apps')->ignore($website)
],
]);
don't you need to pass duplicate column in ignore Rule To instruct the validator to ignore the website domain, except for it self ? for example like
Rule::unique('apps')->ignore($website->id)
please try this one . it helps to solve your problem
use exception and validator in top of the file
use Exception;
use Validator;
$rules = [
'subDomainName' => 'required|unique:sub_domain_name',
];
$validator = Validator::make($request->all(), $rules, $message);
if ($validator->fails()) {
throw new Exception(implode('\n', $validator->errors()->all()));
}
sub_domain_name : this is database column name
I'm trying to update a user, as an admin.
I'm changing the username, but it says email must be unique.
How do I fix this.
public function update($id, PutUser $request)
{
if (auth()->id() == $id) {
return redirect()->back()->withFlashDanger('Permission Denied, You can not edit own profile here.');
}
$user = User::find($id);
$user->update((array_merge($request->validated(), ['county' => request('county')])));
//Update model_has_roles model with assignees_roles
return redirect()->route('users.index')->withFlashSuccess(trans("alerts.users.updated"));
}
This is the request class
public function authorize()
{
return true;
}
public function rules()
{
$user_id = $this->input('id');
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
}
}
I keep getting a failed email validation. 'Email has already been taken'. Any idea
You are missing a comma after the email label in your validation:
return [
'name' => 'required|string',
'username' => 'required',
'email' => 'required|email|unique:users,email,'.$user_id,
'gender' => 'required',
'phone' => 'sometimes|numeric',
'address' => 'sometimes|string',
'country_id' => 'required',
];
Since Laravel 5.3 (I believe), you can also use rule builders for more descriptive validation rules. Those are better to read and interpret for humans so it would result in a lower error rate:
use Illuminate\Validation\Rule;
return [
'email' => [
'required',
Rule::unique('users', 'email')->except($user_id),
]
];
https://medium.com/#tomgrohl/why-you-should-be-using-rule-objects-in-laravel-5-5-c2505e729b40
I used laravel 5.2 to build my app but suddenly validation doesn't work out on registration`new users
Route::post('/register','userController#store');
my function on validation part for storing users details
public function store(Request $request)
{
$this->validate($request,[
'fname' => 'required|max:50',
'lname' => 'required|max:50',
'email' => 'required|email|unique:users',
'phone' => 'required|unique:users',
'provider' => 'required',
'company' => 'required',
'password' => 'required|min:8',
'IDtype' => 'required',
'IDnumber' => 'required',
'region' => 'required|max:32',
'signature' => 'required'
]);
}
Things were working well but now return
"fname":["validation.required"],"lname":["validation.required"],"email":["validation.required"],"IDtype":["validation.required"],"IDnumber":["validation.required"]} returned as response
`
You shoud use $request->all() instead of $request
public function store(Request $request)
{
$this->validate($request->all(),[
........
]);
}
In Laravel 5.5 you can call the validate method on request and it's recommended
$request->validate($rules);