How to custom validation with input value as name already been taken? - laravel

In controller
public function store(Request $req)
{
$req->validate([
'username' => 'required|unique:users',
]);
$users = new Users();
$users->username = $req->username;
$users->save();
return redirect()->route('list.users');
}
The username validation return as The username has already been taken.
I am typing the username field as JHON and i would to return the validation as like: The JHON has already been taken. ?

I believe you can use :input when defining custom validation messages.
public function store(Request $req)
{
Validator::make($req, [
'username' => 'required|unique:users',
], [
'unique' => 'The :input username has already been taken.',
]);
$users = new Users();
$users->username = $req->username;
$users->save();
return redirect()->route('list.users');
}

To make your code cleaner, you should change the localization of the "unique" validation error
Go to the file "resources/lang/en/validation.php" (or change the "en" part with your language's iso code) and change the "unique" value.
From:
'unique' => 'The :attribute has already been taken.',
To:
'unique' => 'The :attribute :input has already been taken.',
This way, you should get the following message
The username JHON has already been taken.

$req->validate([
'username' => 'required|unique:users,username',
]);
This is the syntax for using unique:
unique:table,column
https://laravel.com/docs/7.x/validation#rule-unique

Related

How to make 2 different Laravel Validation messages for the same rule that has 2 different arguments?

Hello I have Laravel validation request with these rules
public function rules()
{
return [
'email' => 'unique:users,email|required|unique:invitations,email',
'name' => 'string|required',
];
}
I want that "unique:users,email" would display one message and "unique:invitations,email" display other message. How to do that?
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
It always returns default message for "unique" rule.
'unique' => 'The :attribute has already been taken.',
I am not sure if this will work but can you try these
public function messages()
{
return [
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
//or
'email.unique:users,emai' => 'This E-Mail address is already registered.',
'email.unique:invitations,email' => 'Invitation to this E-Mail address is
//you may even try it without the ,fieldname
'email.unique:users' => ''
];
}
Try to define like
'email.unique:users,emai' => ....,
'email.unique:invitations,emai' => ....,

Users Controller does not exist

I'm building a CMS in Laravel 5.8 with an in-built Authentication system. My app was working fine but suddenly it starts giving me an error as ReflectionException : Class App\Http\Controllers\Users does not exist on command php artisan route:list -v. However, if i define a new resource route, then that new route page works fine. It means, route file is getting saved but gives error while listing the routes.
I have not created any file named as Users but my user controller file name is UserController
Below is the structure of my application:
cms -> project folder
app
Http
Controllers
Auth
RegisterController.php
LoginController.php and other Auth files
backend
UserController.php and my other controller files
Below is my route file
Auth::routes();
Route::group(['as'=>'cms.' ,'prefix'=>'cms'],function(){
Route::get('/', 'backend\Dashboard#index')->name('dashboard');
Route::resource('/user-management', 'backend\UserController');
});
Below is my UserController file residing in backend folder
<?php
namespace App\Http\Controllers\backend;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redirect;
use Auth;
use App\Models\backend\Admin;
use App\Models\backend\Menu;
use App\Models\backend\Submenu;
use Config;
use illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function __construct()
{
$this->middleware('auth:admin');
}
public function AuthRouteAPI(Request $request)
{
return $request->user();
}
public function index()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
$cms_users = Admin::withTrashed()->get();
return view('backend.pages.users.index', ['arrUserMenu'=>$arrUserMenu, 'cms_users'=>$cms_users]);
}
public function create()
{
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.create', ['arrUserMenu'=>$arrUserMenu]);
}
public function store(Request $request)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|unique:cms_users,email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrname' => 'required|min:'.Config::get('cms_const.USER_ID_MIN_LEN').'|max:'.Config::get('cms_const.USER_ID_MAX_LEN').'|regex:/(^[A-Za-z0-9._]+$)+/|unique:cms_users,username',
'usrpwd' => 'required|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.unique' => 'Email already exist',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrname.required' => 'Please enter the user name',
'usrname.min' => 'User name should not be less then '.Config::get('cms_const.USER_ID_MIN_LEN').' characters',
'usrname.max' => 'User name should not be more then '.Config::get('cms_const.USER_ID_MAX_LEN').' characters',
'usrname.regex' => 'Only Alphabets, Numbers, Dot and Underscore allowed in user name',
'usrname.unique' => 'User name already exist',
'usrpwd.required' => 'Please enter the password',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
Admin::create([
'name' => $request->name,
'username' => $request->usrname,
'password' => bcrypt($request->usrpwd),
'email' => $request->usrmail,
]);
return redirect()->route('cms.user-management.index')->with('success','New user account created successfully.');
}
public function edit($id)
{
if(!$id)
{
return redirect()->route('cms.user-management.index');
die;
}
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
// GET THE CURRENT LOGGED IN USE
$user = Auth::user();
// CODE FOR GETTING MENU LIST FOR CURRENT USER STARTS
$menutable = (new Menu)->getTable();
$arrUserMenu = $user->getUserMenus($menutable);
// CODE FOR GETTING MENU LIST FOR CURRENT USER ENDS
return view('backend.pages.users.edit', ['arrUserMenu'=>$arrUserMenu, 'arrRecord'=>$arrRecord]);
}
public function update(Request $request, $id)
{
$rules = [
'name' => 'required|min:'.Config::get('cms_const.USER_NAME_MIN_LEN').'|max:'.Config::get('cms_const.USER_NAME_MAX_LEN').'|regex:/(^[A-Za-z ]+$)+/',
'usrmail' => 'required|email|max:'.Config::get('cms_const.USER_EMAIL_MAX_LEN'),
'usrpwd' => 'nullable|min:'.Config::get('cms_const.USER_PWD_MIN_LEN').'|max:'.Config::get('cms_const.USER_PWD_MAX_LEN').'|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-_]).{7,}$/'
];
$msgs = [
'name.required' => 'Please enter name',
'name.min' => 'Name should not be less then '.Config::get('cms_const.USER_NAME_MIN_LEN').' characters',
'name.max' => 'Name should not be more then '.Config::get('cms_const.USER_NAME_MAX_LEN').' characters',
'name.regex' => 'Only alphabets are allowed in name',
'usrmail.required' => 'Please enter email',
'usrmail.email' => 'Invalid email',
'usrmail.max' => 'Email should not be more then '.Config::get('cms_const.USER_EMAIL_MAX_LEN').' characters',
'usrpwd.min' => 'Password should not be less then '.Config::get('cms_const.USER_PWD_MIN_LEN').' characters',
'usrpwd.max' => 'Password should not be more then '.Config::get('cms_const.USER_PWD_MAX_LEN').' characters',
'usrpwd.regex' => 'Invalid password format',
];
$this->validate($request, $rules, $msgs);
$arrRecord = Admin::find($id);
if(is_null($arrRecord))
{
return redirect()->route('cms.user-management.index')->withErrors(['error'=>'Record you are trying to edit does not exist']);
die;
}
$arrRecord->name = $request->input('name');
$arrRecord->email = $request->input('usrmail');
if($request->input('usrpwd'))
{
$arrRecord->password = bcrypt($request->input('usrpwd'));
}
$arrRecord->save();
return redirect()->route('cms.user-management.index')->with('success','User account details updated successfully.');
}
public function destroy($id)
{
try
{
$user = Admin::findOrFail($id);
$user->delete();
return response()->json(['success'=>'Record successfully deleted', 'status'=>'Suspended']);
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
return response()->json(['error'=>'Record you are trying to delete does not exist']);
}
}
}
I have tried the below commands and they all run successfully but none resolved the error
php artisan clear-compiled
composer dump-autoload
php artisan optimize
php artisan route:cache
Don't know from where this Users controller class in being referenced.
Can anyone help me in this regard as I'm badly stuck in my development.
Much Regards,
Javed
#ClémentBaconnier the error is resolved now. I made the changes in api.php to Route::middleware('auth:api')->get('/user', 'backend\Users#AuthRouteAPI'); and now all my routes are listed. Thanks u soooo much for ur advice.

Laravel send mail with multiple check box value

i'm trying to make inquiry form where costumer fill up form then check the value on the checkbox then once they submit form will send email to me listing all the information the customer selected, now problem is i want to change this[event_id,requirement_id] instead of id replace it with name those two id parameter is from my two model listed below.
Model:
Event:[id,name]
Requirement:[id,name]
Controller:
public function store(Request $request)
{
$summary=[
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $request->event_id,
'requirement' => $request->requirement_id
];
return $summary;
Mail::send('emails.contact-message',[
],function($mail) use($summary){
$mail->from('myemail#gmail.com', 'tester');
$mail->to('myemail#gmail.com')->subject('Contact Message');
});
return redirect()->back();
}
This is the result of my return request:
{"name":"myname","email":"myemail#gmail.com","company":"mycompany","event":["1","2"],"requirement":["1","2"]}
As you can see the array Event has value of 1 and 2 i wanted to replace it with its name output should be [Wedding,Birthday] i'm sorry for my bad english hope you understand me..
Well, you'd need to pull the name from your models.
The following should do the trick:
$events = App\Event::whereIn('id', $request->event_id)
->get()
->pluck('name')
->toArray();
$requirements = App\Requirement::whereIn('id', $request->requirement_id)
->get()
->pluck('name')
->toArray();
Obviously, replace name in the above example with the actual name field in your models. This is just an example.
$events and $requirements will both be an array containing the names matching the ids you are supplying in your request.
You also need to change your $summary array as follows:
$summary = [
'name' => $request->fullname,
'email' => $request->email,
'company' => $request->company,
'event' => $events
'requirement' => $requirements
];

how to create Custom Validation Rule for during Update a record in CakePHP

I have added a rule to check the previous password on update user record, but the rule also applies to creating a record, I have added 'update' but still, it's not working.
$validator
->scalar('password')
->maxLength('password', 25)
->notEmpty('password', 'Password is required', 'create')
->allowEmpty('password', 'update')
->add('password', 'validFormat', [
'rule' => ['custom', '/^(?=.*[!#$])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{6,16}$/i'],
'message' => __('Minimum 6 character & alphanumeric with one symbol(!#$) is Required.'),
'allowEmpty' => true
])
->add('password', 'custom', [
'rule' => function($value, $context){
$user = $this->get($context['data']['id']);
if ($user) {
if (!(new DefaultPasswordHasher)->check($value, $user->password)) {
return true;
}
}
return false;
},
'message' => 'You cannot use your previous password',
'allowEmpty' => true
], 'update');
Adding updated does not do anything as it is not something that CakePHP supports there.
If you read Custom Validation Rules you will see that you can use $context['newRecord'] to determine if this is an update or create.
So, the first line in your validation function could be something like
if ($context['newRecord']){
return true; //new passwords are always valid!
}
Alternative way would be to check the $user variable and add an else branch
if($user){
//you already have code here
}else{
//add this else to return TRUE because for new user, new password is OK
return true;
}

Do custom error messages in Laravel 4.2

I'm new in Larvel 4.2 here! How do I do a custom error messages in Laravel 4.2? And where do I put these codes? I've been using the defaults and I kind of wanted to use my own.
Did you try something? http://laravel.com/docs/4.2/validation#custom-error-messages
Did you use Google? Check the documentation (official) it has everything. Be less lazy.
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make($input, $rules, $messages);
To add to the answer given by slick, here is how you could use it in a real example of a store function inside a controller:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'id1' => 'required|between:60,512',
'id2' => 'required|between:60,512',
'id3' => 'required|unique:table',
], [
'id1.required' => 'The first field is empty!',
'id2.required' => 'The second field is empty!',
'id3.required' => 'The third field is empty!',
'id1.between' => 'The first field must be between :min - :max characters long.',
'id2.between' => 'The second answer must be between :min - :max characters long.',
'id3.unique' => 'The third field must be unique in the table.',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
//... Do something like store the data entered in to the form
}
Where the id should be the ID of the field in the form you want to validate.
You can check out all the rules you can use here.

Resources