I don't know how to get the query string array to validate in Laravel Validation.
here is my code
public function addUserByAdmin(Request $request){
$this->validate($request,[
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
$uesrAction = new UserAction($this->repository);
$user = $uesrAction->addUser($request->input('phone'),$request->input('password'),$request->input('name'),$request->input('fullname'),$request->input('position'));
if($user){
return response()->json(['success' => 'success','user'=>$user]);
}
return response()->json(['success' => 'fail']);
}
but validation doesn't work.Then I tried Validation::make() method and also didn't work.
My URL be like
http://localhost:8000/admin/users/add-user?phone=abcdefg&password=erer&name=ere&fullname=rere&position=343
If you are using laravel 5.5, change your code as follows:
public function addUserByAdmin(Request $request){
$validatedData = $request->validate([
'name' => 'required',
'fullname' => 'required',
'password' => 'required',
'position' => 'required',
'phone' => 'required'
]);
// ...
}
One of the features that was added in this update is that other way to use the validate() method:
More info:
https://laravel.com/docs/5.5/validation#quick-writing-the-validation-logic
https://laravel.com/docs/5.5/releases
Related
I'm using this code for User Sign Up in Laravel:
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
$user = User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'phone' => $validatedData['phone'],
'type' => $validatedData['type'],
'verified' => $validatedData['verified'],
'password' => Hash::make($validatedData['password']),
]);
$token = $user->createToken('auth_token')->accessToken;
return response()->json([
'user' => $user,
'access_token' => $token,
'token_type' => 'Bearer',
]);
}
As you can see , some of my field are unique , so I want to display a message in my front side that displays the error from the back side.
Exemple : When a user enters a used phone number , I want to return an error saying : this phone number has been used .
How can I achieve this ? Thank you.
You can get a User record from the database by phone. If the record exists, then do your logic
class UsersController extends Controller
{
public function register(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:8',
'phone' => 'required|unique:users',
'type' => 'boolean',
'verified' => 'boolean'
]);
// get a user record by phone
$record = User::where('phone', $validatedData['phone'])->find();
if (!empty($record)) {
return response()->json([
'error' => 'this phone number has been used'
])
}
//.....
}
ok, I'm trying to login the users after success registration into their panels. the database line built successfully. but alternately user login become successful but once not.
Here is the Request Controller Code:
$request->merge(['phone'=> '09123456789']);
$request->merge(['name' => 'User']);
$request->merge(['password' => 'pass123456789']);
$request->merge(['email' => 'user#email.com']);
$credentials = $request->validate([
'name' => 'required',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required',
'email' => 'required',
]);
User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $credentials['phone'],
'password' => Hash::make($credentials['password'])
]);
if (Auth::attempt($credentials)) {
$request->session()->regenerate();
return redirect()->route('panel');
}
The Model:
protected $fillable = [
'name',
'phone',
'email',
'password',
];
let me know if I didn't describe perfectly
First, I would stop using validation in the controller and use form request validation instead. It's been the standard since Laravel 5.
Try this simplified code using Auth::login() instead:
public function createUser(Request $request)
{
$request->validate([
'name' => 'required|string|max:64',
'phone' => 'required|regex:/^([0-9\s\-\+\(\)]*)$/',
'password' => 'required|string|max:64',
'email' => 'required|email|max:64',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'password' => Hash::make($request->password),
]);
Auth::login($user);
return redirect()->route('panel');
}
I want to know how can I save two models which has one relationship in my models. I don't know how to save it but I need the ID for my patient model to assign to my scale model.
Here is my PatientController.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$scales = new Scale;
$patient->name = $request->input('name');
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->save();
return redirect('/patients')->with('success', 'Paciente creado.');
}
I try this code but get error.
DB::transaction(function() use ($patient, $scales) {
$patient = $patient->save(); //Patient Exists First
Patient::find($patient->id)->scales()->save($scales)
});
You could try something like this:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->name;
$patient->save();
$patient->scale()->create(['patient_id' => $patient->id, 'sd_abc_1_old' => $request->sd_abc_1_old]);
);
return redirect('/patients')->with('success', 'Paciente creado.');
}
If the model uses a hasOne() relation like you said then the code show work, with a bit of modification of course.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = Patient::create([
'name' => $request->input('name'),
]);
$scale = Scale::create([
'patient_id' => $patient->id,
'sd_abc_1_old' => $request->sd_abc_1_old,
]);
return redirect('/patients')->with('success', 'Paciente creado.');
}
First create and store base model and referencing it save related model
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'birth' => 'required',
'nacionality' => 'required',
'adress' => 'required',
'phone' => 'required',
'living_method' => 'required',
'responsable' => 'required',
]);
//Create Patient
$patient = new Patient;
$patient->name = $request->input('name');
$patient->save();
$scales = new Scale;
$scales->sd_abc_1_old = $request->input('sd_abc_1_old');
$patient->scales()->save($scales);
return redirect('/patients')->with('success', 'Paciente creado.');
}
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);