I want to remove validation on the name in laravel 6 on creating a new user. The user is created successfully but when I enter a name with space or capital letters, the login page opens up. But if I remove all spaces from the name everything works fine with the following code.
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
$username = slugify($data['name']) . "-" . mt_rand(10000, 99999);
return User::create([
'name' => $data['name'],
'username' => $username,
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
blade.php code
https://codeshare.io/5e1kX7
Try
//...
'name' => ['required', 'string', 'regex:/^[a-zA-Z0-9\s]+$/', 'max:255'],
//...
I did it by adding regex in the validation
'name' => ['required', 'string','regex:/^[\pL\s\-]+$/u', 'max:255'],
Related
Could I know how to take the user Id to Request an update? for example, when I updated the user and password. But, except email. At that time, It showed "the message that the email is already taken. When I searched for solutions, I found to solve with the user id. I know this question is asked many times. But, I didn't get any suitable answer for me. Could you help me, please?
This is my Controller Code
public function edit(Users $request,$id){
$users=User::whereId($id)->firstorFail();
$users->name = $request->get('name');
$users->email = $request->get('email');
$users->password = Hash::make($request->get('password'));
$users->role = $request->get('role');
$users->update();
$request->session()->forget('editvalue');
$userdata = User::paginate(4);
// session()->flash('status', 'User has been successfully added.');
return view('pages.auth.register', compact('userdata'))->with('status','User has been successfully added.');
}
This is my Request Form. I want to take id value in this. When I take value, it is showing the message that Trying to get property 'id' of non-object
public function rules() {
return [
'name' => 'required', 'string', 'max:255',
'email' => 'sometimes','required', 'string', 'email', 'max:255', 'unique:users,'. $this->users->id,
'password' => 'required', 'string', 'min:8', 'confirmed',
'role' => 'required', 'string',
];
}
This is my web.php
Route::get('users/edit/{id}', 'UsersController#editscreen');
Route::post('users/edit/{id}', 'UsersController#edit');
You should also put the column name to the rule,
the pattern should be unique:table,column,except_id
Can you replace your RequestForm with this:
public function rules()
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['sometimes','required', 'string', 'email', 'max:255', 'unique:users,email,'. $this->users->id],
'password' => ['required', 'string', 'min:8', 'confirmed'],
'role' => ['required', 'string'],
];
} }
I think you can't validate {id} in the request class but you can validate with regex in the route. (My Example is for laravel 8 but the principle remains the same)
Route::post('/users/edit/{id}', [UsersController::class, 'editscreen'])
->where('id', '[0-9]+');
I got with this.
use Illuminate\Validation\Rule;//import Rule class
public function rules()
{
return [
'name' => 'required', 'string', 'max:255',
'email' => ['sometimes','required', 'string', 'email', 'max:255',
Rule::unique('users')->ignore($this->id),
],
'password' => 'required', 'string', 'min:8', 'confirmed',
'role' => 'required', 'string',
];
}
I just encountered this problem and managed to solve by adding $this->id only.
public function rules()
{
return [
'name' => ['required', 'string', 'max:255']
'email' => ['required', 'string', 'unique:users,email,' . $this->id]
];
}
If I change validate by validator->fails return redirect..... I get error because login want an instance of $user and I send a response.
This defaults work well but not for me
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
])->validate();
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
Thats give me a:
Illuminate\Auth\SessionGuard::login(): Argument #1 ($user) must be of type Illuminate\Contracts\Auth\Authenticatable, Illuminate\Http\RedirectResponse given, called in ....endor/laravel/fortify/src/Http/Controllers/RegisteredUserController.php on line 57
public function create(array $input)
{
$validator = Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => $this->passwordRules(),
'terms' => Jetstream::hasTermsAndPrivacyPolicyFeature() ? ['required', 'accepted'] : '',
]);
if($validator->fails()) {
return Redirect::to(URL::previous() . "#my-anchor")->withInput()->with('error', $validator->messages()->first());
} //Thats I want
return User::create([
'name' => $input['name'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
I don't did this before but maybe you can find the way to customize it. The CreateNewUser is called in the RegisteredUserController's store method, and the first return an User's instance. So in this you can
if($validation->fails())
return $validation->messages()->first();
and in the store method
public function store(Request $request, CreatesNewUsers $creator): RegisterResponse
{
$user = $creator->create($request->all()));
if($user instanceof User::class) {
event(new Registered($user);
$this->guard->login($user);
return app(RegisterResponse::class);
} else
return Redirect::to(URL::previous()."#my-anchor")->withInput()->with('error', $user);
}
Try this, but I suggest you if works extends this Register controller and just modify this store method
I hope you can help me, I wanna customize the registercontroller from Laravel, I have this, but after the user is registered send me a JSON of data, how can I do for don't send me the JSON and redirect to the HomeController.
Thanks.
PD. Sorry for my English.
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
return User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
return redirect()->action('HomeController#index'),
]);
}
Laravel 5.5: Execute a method before registration
HomeController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('index');
}
}
You are returning the return value of User::create() which will be a User object which gets converted to json when returned as a response.
Also since your HomeController is protected by 'auth' middleware you need to login the user before redirecting to '/home'
use Illuminate\Support\Facades\Auth;
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => ['required', 'string', 'max:255'],
'nombre' => ['required', 'string', 'max:255','unique:users'],
'telefono' => ['required', 'numeric', 'max:99999999', 'min:00000000'],
'direccion' => ['required', 'string', 'max:255'],
'sueldo' => ['numeric','min:0.01','max:0.99'],
//'foto' => ['string', 'max:255'],
'email' => ['string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:4', 'confirmed'],
]);
if ($request->hasFile('foto')) {
$request = request();
$file = $request->file('foto');
$nom_imagen = time().".".$file->getClientOriginalExtension();
$upload_path = 'imagenes/';
$profile_image_url = $upload_path . $nom_imagen;
$success = $file->move($upload_path, $nom_imagen);
} else {
$nom_imagen = '';
}
$user = User::create([
'name' => $request->input('name'),
'nombre' => $request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password']),
]);
Auth::guard()->login($user);
return redirect('/home');
}
Move the redirect after create user , try like this
User::create([
'name' => $request->input('name'),
'nombre' =>$request->input('nombre'),
'telefono' => $request->input('telefono'),
'direccion' => $request->input('direccion'),
'sueldo' => $request->input('sueldo'),
'email' => $request->input('email'),
'foto' => $nom_imagen,
'password' => Hash::make($request['password'])
]);
return redirect()->action('HomeController#index'),
I have a user settings form with 4 fields - first and last name, date of birth and username. The username is unique field in the database. The issue that I run into is when I already have set your username but after that want to update the last name or first name it always throws an error that the username is already in use. Can I somehow check if the username hasn't been changed to not validate it? Only to validate the other fields?
public function update(Request $request)
{
$user = Auth::user();
$this->portfolioValidator($request->all())->validate();
$user->username = $request->username;
$user->contact->first_name = $request->first_name;
$user->contact->last_name = $request->last_name;
$user->contact->save();
$user->save();
return response()->json(['message' => 'The changes have been saved'], 201);
}
protected function portfolioValidator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string'],
'last_name' => ['required', 'string'],
'username' => ['required', 'string', 'min:4', 'max:30', 'unique:users'],
]);
}
You can update your unique rule to ignore the current user as described here:
use Illuminate\Validation\Rule;
protected function portfolioValidator(array $data)
{
return Validator::make($data, [
'first_name' => ['required', 'string'],
'last_name' => ['required', 'string'],
'username' => ['required', 'string', 'min:4', 'max:30', Rule::unique('users')->ignore(Auth::user()->id)],
]);
}
I'm creating two different registration (for admin and user). But the username->unique in the validator is only for table users.
protected function validator(array $data)
{
return Validator::make($data, [
'firstname' => ['required', 'string', 'max:255', 'min:3'],
'middlename' => ['required', 'string', 'max:255', 'min:3'],
'lastname' => ['required', 'string', 'max:255', 'min:3'],
'username' => ['required', 'string', 'max:255', 'min:3', 'unique:users'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
]);
}
validate unique username for user registration from the users table and validate unique username for admin registration from the admins table.
You could use the route name or something similar, from the current request to determine which rules have to get used.
protected function validator(array $data)
{
$route = Request::route()->getName();
$rules = [
'firstname' => ['required', 'string', 'max:255', 'min:3'],
'middlename' => ['required', 'string', 'max:255', 'min:3'],
'lastname' => ['required', 'string', 'max:255', 'min:3'],
'password' => ['required', 'string', 'min:6', 'confirmed'],
];
// whatever your route name or identifier to differentiate between
// user and admin registration may be.
if ($route === 'registration.user') {
$rules = $rules + [
'username' => ['required', 'string', 'max:255', 'min:3', 'unique:users'],
];
}
return Validator::make($data, $rules);
}
A Validator should only validate data, it's bad to couple it with concepts about routes etc...
I would create a custom Validator class which will take a table name as parameter.
Then you can instantiate that validator with the correct table parameters in your controller (which will be aware about route, request etc...)