My form validation is not working in Laravel. How can I update my form with validation in Laravel?
You can check my code here-
public function update(Request $request, $id)
{
$id->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
return redirect('/info');
}
You need to call validate on $request, like this-
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
Here is the full code-
public function update(Request $request, $id)
{
$request->validate([
'Name'=>'required',
'UserName'=>'required',
'Password'=>'required|min:6',
'email'=>'required|email',
]);
if (!$validator->fails()) {
$updateInfo= Info::findOrFail($id);
$updateInfo->user_id = $request->input('user_id');
$updateInfo->Name = $request->input('Name');
$updateInfo->UserName = $request->input('UserName');
$updateInfo->Password = $request->input('Password');
$updateInfo->save();
} else {
\Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
return redirect('/info');
}
I have added one more condition in the code to handle the validation errors. If validation fails then it will redirect back with your inputs as well as the validation error messages. Make sure you have error session flash in your blade views to show the errors.
For me this is best way , i can keep on track on query and other exceptions by putting it in try catch block
public function update(Request $request, $id)
{
try{
$validator = Validator::make($request->all(), [
'name' => 'required',
'UserName' => 'required',
'Password' => 'required',
'email' => 'required|email',
]);
if($validator->fails()) {
return redirect()
->route('path_to_edit_form')
->withErrors($validator)
->withInput();
}
Info::where('id',$id)->update([
'user_id' => $request->get('user_id'),
'Name' => $request->get('Name'),
'UserName' => $request->get('UserName'),
'Password' => $request->get('Password'),
]);
return back()->with([
'alert_type' => 'success',
'message' => 'User info updated successfully.'
]);
}catch(\Exception $e){
return back()->with([
'alert_type' => 'danger',
'message' => $e->getMessage()
]);
}
}
Related
so I have this store function at my Controller
public function store(Request $request)
{
Penghuni::create([
'nama_penghuni' => $request->nama_penghuni,
'email' => $request->email,
'phone' => $request->phone,
'tower' => $request->tower,
'no_unit' => $request->no_unit
]);
User::create([
'name' => $request->nama_penghuni,
'email' => $request->email,
'password' => Hash::make($request['password']),
'role' => 'penghuni',
]);
return redirect(route('penghuni.index'));
}
what I want is make sure both insert is success, because the current result I got is when Penghuni create is done but the user is fails it keeps getting redirected
hope someone can help, I use laravel 5.8
thank you
This Code is Perfect check other things.
public function store(Request $request)
{
Penghuni::create([
'nama_penghuni' => $request->nama_penghuni,
'email' => $request->email,
'phone' => $request->phone,
'tower' => $request->tower,
'no_unit' => $request->no_unit
]);
User::create([
'name' => $request->nama_penghuni,
'email' => $request->email,
'password' => Hash::make($request['password']),
'role' => 'penghuni',
]);
return redirect(route('penghuni.index'));
}
1. Model
Penghuni and user Model must added this Line
protected $guarded = [];
Other Solution
public function store(Request $request)
{
$penghuni = new Penghuni;
$penghuni->nama_penghuni = $request->nama_penghuni;
$penghuni->email = $request->email;
$penghuni->phone = $request->phone;
$penghuni->tower = $request->tower;
$penghuni->no_unit = $request->no_unit;
$penghuni->save();
$user = new User;
$user->name = $request->nama_penghuni;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->role = 'role';
$penghuni->users()->save($user);
return redirect(route('penghuni.index'));
}
You can wrap your queries in a database transaction like so:
DB::transaction(function () use ($request) {
// queries here
});
return redirect(route('penghuni.index'));
Or something like this, depending on your use-case.
DB::beginTransaction();
try {
// queries here
// all good
DB::commit();
return redirect(route('penghuni.index'));
} catch (\Exception $e) {
// something went wrong
DB::rollback();
}
You can read more about database transaction here: https://laravel.com/docs/8.x/database#database-transactions
here is my code for validate request
public function signup(Request $request) {
$validatedData = $request->validate([
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
]);
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
when I try this validation not working how can I fix this?
for example
when this data for validation
'name' = "",(empty)
'email' = "test2#mail.com"
'password'= "test2#mail.com"
and I expect my validation should work but its throw BadMethodCallException error
here is my route (via API)
<?php
Route::group([
'middleware' => 'api',
'prefix' => 'auth'
], function ($router) {
Route::post('login', [App\Http\Controllers\AuthController::class, 'login']);
Route::post('logout', [App\Http\Controllers\AuthController::class, 'logout']);
Route::post('refresh', [App\Http\Controllers\AuthController::class, 'refresh']);
Route::post('me', [App\Http\Controllers\AuthController::class, 'me']);
//custom
Route::post('signup', [App\Http\Controllers\AuthController::class, 'signup']);
});
NOTE: am check this VIA postman
You can do it another way with the laravel Validator class. Please add use Validator class before your class declaration.
Then create your function like this:
public function signup(Request $request) {
$validate = array(
'name' => 'required',
'email' => 'required|unique:users|max:255',
'password' => 'required|min:6|confirmed',
);
$validatedData = Validator::make($request->all(),$validate);
if(!validatedData->fails()) {
return $validatedData->errors();
}else{
$data = array();
$data['name'] = $request->name;
$data['email'] = $request->email;
$data['password'] = Hash::make($request->password);
DB::table('users')->insert($data);
return $this->login($request);
}
}
I want to store data through api. It's working but problem is when I add validation it does not give me corresponding message . How can I fix it? Thanks in advance
Here is my route
Route::post('api/add_user', 'TestApiController#store');
Here is my controller
public function store(Request $request)
{
$validation = Validator::make(Request::all(), [
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
if ($validation->errors()) {
return $errors->toJson();
} else {
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
}
to handle that your method should be like this :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'phone' => 'required',
'email2' => 'required|email'
]);
if($validator->fails()){
// here we return all the errors message
return response()->json(['errors' => $validator->errors()], 422);
}
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
// 201 http code means that the server has proceced your request correctly
return response()->json([], 201);
}
You don't have to manually do this. simply
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'phone' => 'required',
'email' => 'required'
]);
$testApi = new testApi();
$testApi->name = $request->name;
$testApi->phone = $request->phone;
$testApi->email = $request->email;
$testApi->save();
return "ok";
}
this will automatically handles validation and returns error message when invalid.
Update
if you wanna stick with your approach. this is where you need to change.
if ($validation->fails()) {
return $validation->errors();
}
I try to register user with send connfirmation mail at the samme time.but the page is reloaded there is no data stored in db and also not sending the confirmation email.
RegisterController.php
protected function create(array $data)
{
return User::create([
'title' => $data['title'],
'fname' => $data['fname'],
'lname' => $data['lname'],
'company' => $data['company'],
'email' => $data['email'],
'phone' => $data['phone'],
'people' => $data['people'],
'sdate' => $data['sdate'],
'notes' => $data['note'],
'password' => Hash::make($data['password']),
]);
}
public function register(Request $request)
{
//dd($request->all());
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
Mail::to($user->email)->send(new ConfirmationEmail($user));
return back()->with('status','Please confirm your email address...');
// $this->guard()->login($user);
// return $this->registered($request, $user)
// ?: redirect($this->redirectPath());
}
//confirmation email code
public function confirmEmail($token)
{
User::whereToken($token)->firstOrFail()->confirmEmail();
return redirect('/user/login')->with('status', 'You are now confirmed. Please login.');
}
I have a Laravel Lumen API. I'm seeing an issue with the update functionality.
In my controller, the code for updating an item is:
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required',
]);
$todo = Todo::find($id);
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
I can update the todo item using:
http://lumen-todo.app/api/51?name=test&description=test&completed=1
however was hoping I could send the parameters in a json body, like this
PUT http://lumen-todo.app/api
{
"id": 1
"name": "Test",
"description": "Test",
"completed": 1,
}
For adding items, it works via a json body, so don't understand why it does not work for updates. For info, the 'add item' controller code is here:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
return response()->json(['status' => 'success']);
}
If you want to get the json data from request payload, validate and store it, use
public function store(Request $request)
{
$data = $request->json()->all();
$this->validate($data, [
'name' => 'required',
'description' => 'required',
'completed' => 'required'
]);
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
return response()->json(['status' => 'success']);
}
Instead of doing this:
$todo = new Todo();
$todo->name = $request->name;
$todo->description = $request->description;
$todo->completed = $request->completed;
$todo->save();
Do, this:
use App\Todo;
protected $model;
public function __construct(Todo $model) {
$this->model = $model;
}
$resource = $this->model->find($id);
$resource->fill($request);
$resource->save();
Also, you can do json_decode() function to change your json params to array and use that to validate and save data.