Displaying laravel error messages on redirect - php

I have a form which i am hoping to use to insert some data to mysql. I have setup the validator like this
public function insert_post(){
$rules = array(
'model' => 'required',
'country' => 'required',
'engine' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
echo '<pre>';
print_r($messages);
echo '</pre>';
return Redirect::to('create-posts')
->withErrors($validator);
}
else {
$i = new Text;
$i->model = request('model');
$i->country = request('country');
$i->engine = request('engine');
$i->save();
return redirect('/');
}
}
My create-posts route looks like this.
public function create_post(){
return view('create-posts');
}
However, its not displaying the error since i think i am loading a fresh create-posts and the validator messages are lost.
view code
<div class="form-group">
<label for="inputEmail" class="control-label col-xs-2">Model</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="inputEmail" name="model" placeholder="Model">
#if ($errors->has('model')) <p class="help-block">{{ $errors->first('model') }}</p> #endif
</div>
</div>
Is that what's the cause?.

In case you want to return to the last view, you can use:
return Redirect::back()->withErrors($validator);
Instead of return Redirect::to('create-posts')->withErrors($validator);.

Related

Uploading image from input field and still getting validation error saying that field is required

Route Code:
Route::group(['middleware' => 'auth', 'prefix' => 'admin'], function(){
Route::resource('gallery', GalleryController::class);
});
The Form I'm Using to Upload the File:
<form action="{{ route('gallery.store') }}" method="post" enctype="multipart/form-data">
#csrf
<div class="input-group mb-3">
<div class="custom-file">
<input type="file" class="custom-file-input" name="gallery_img" id="inputGroupFile01">
<label class="custom-file-label" for="inputGroupFile01">Choose file</label>
</div>
</div>
#error('gal_img')
<span class="text-danger">{{ $message }}</span>
#enderror
<div class="input-group-append">
<div class="col-sm-10" style="padding-left: 1px;">
<button type="submit" class="btn btn-dark">Save</button>
</div>
</div>
Controller Code:
public function store(GalleryRequests $request)
{
$gal_img = $request->file('gallery_img');
$gal_file = date('YmdHi').$gal_img->getClientOriginalName();
$gal_img->move(public_path('upload/gallery'), $gal_file);
$save_path = 'upload/gallery/'.$gal_file;
Gallery::insert([
'gal_img' => $save_path
]);
$notification = array(
'message' => 'Slider Inserted Successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Request file validation:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gal_img' => 'required'
];
}
public function messages(){
return [
'gal_img.required' => 'Please Select an Image First',
];
}
The error I get when trying to save after selecting an Image:
Trying to figure out what I've done wrong for hours and am so frustrated right now, please help me to resolve this issue.
Thanks in advance.
Field in form is named gallery_img so that name has to be checked:
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'gallery_img' => 'required'
];
}
public function messages()
{
return [
'gallery_img.required' => 'Please Select an Image First',
];
}

How do I redirect to another page after form submission in Laravel

form
When i submit the form it redirects back to the form itself, can anyone help me?
<form action="/jisajili" method="POST">
#csrf
<div class="card-panel z-depth-5">
<h5 class="center red-text">Jiunge Nasi</h5>
<div class="input-field">
<i class="material-icons prefix">account_circle</i>
<input type="text" name="username" class="validate">
<label>Jina lako</label>
</div>
<div class="input-field">
<i class="material-icons prefix">phone</i>
<input type="number" name="phone" class="validate">
<label>Nambari ya simu</label>
</div>
....
</p>
<input type="submit" name="submit" value="Jiunge" class="btn left col s12 red">
Controller
class registration extends Controller{
public function create(){
return view('jisajili.jiunge');
}
public function store(Request $request){
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$cpassword = $request -> input('cpassword');
$reg->save();
$validated = $request->validate([
'name' => 'required|unique:posts|max:10',
'body' => 'required',
]);
return redirect('home');
}
}
What I would do is first check for the data requirements before you add the object to the database. Also I would add the columns of the models into the Model file to use the Object::create function with an array parameter.
I recomment to use routing in your blade file. I noticed you used action="/route". What you want to do is naming your routes with ->name('route_name') in the route files. To use them in your blade files with the global route function route="{{ route('route_name') }}".
<?php
class PostController extends Controller
{
public function index()
{
return view('post.create');
}
public function store(\Illuminate\Http\Request $request)
{
$validator = Validator::make(
$request->all(),
[
'name' => 'required|unique:posts|max:10',
'body' => 'required'
]
);
// Go back with errors when errors found
if ($validator->fails()) {
redirect()->back()->with($validator);
}
Post::create(
[
'name' => $request->get('name'),
'body' => $request->get('body')
]
);
return redirect()
->to(route('home'))
->with('message', 'The post has been added successfully!');
}
}
What you can do after this is adding custom errors into the controller or add them into your blade file. You can find more about this in the documentation of Laravel.
it redirects you back because of validation error.
change password confirmation name from cpassword into password_confirmation as mentioned in laravel docs
https://laravel.com/docs/7.x/validation#rule-confirmed
update your controller into:
public function store(Request $request){
$validated = $request->validate([
'username' => 'required',
'phone' => 'required',
'email' => 'required',
'password' => 'required|confirmed'
]);
$reg = new regist;
$reg->jina = $request->input('username');
$reg->simuNumber = $request->input('phone');
$reg->email = $request-> input('email');
$reg -> password = bcrypt($request->input('password'));
$reg->save();
return redirect('home');
}
in your blade add the following to display validation errors:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel 5.8 change password functionality

I'm currently trying to make change password functionality to my user profile all my inputs are submitted to the controller, but I think there might be something wrong with my function logic maybe?
Tried dumping request on function and dump was successfully returned. But when wrapping a validation variable around a validation process, the dump was not returned. The request redirects back to the profile page with form data.
Controller
public function updatePassword(Request $request)
{
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
$user = User::find(Auth::id());
if (!Hash::check($request->current, $user->password)) {
return response()->json(['errors' =>
['current' => ['Current password does not match']]], 422);
}
$user->password = Hash::make($request->password);
$user->save();
return $user;
}
View
<form method="POST" action="{{ route('update-password') }}">
#csrf
#method('PUT')
<div class="form-group row">
<label for="old_password" class="col-md-2 col-form-label">{{ __('Current password') }}</label>
<div class="col-md-6">
<input id="old_password" name="old_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="new_password" class="col-md-2 col-form-label">{{ __('New password') }}</label>
<div class="col-md-6">
<input id="new_password" name="new_password" type="password" class="form-control" required autofocus>
</div>
</div>
<div class="form-group row">
<label for="password_confirm" class="col-md-2 col-form-label">{{ __('Confirm password') }}</label>
<div class="col-md-6">
<input id="password_confirm" name="password_confirm" type="password" class="form-control" required
autofocus>
</div>
</div>
<div class="form-group login-row row mb-0">
<div class="col-md-8 offset-md-2">
<button type="submit" class="btn btn-primary">
{{ __('Submit') }}
</button>
</div>
</div>
</form>
The result should return 422/error message at least into the console when 'Current password' is wrong, not just redirect back to view and when the password is correct then return 200/success message (not implemented yet.) to console or view.
try this
public function updatePassword(Request $request){
if (!(Hash::check($request->get('old_password'), Auth::user()->password))) {
// The passwords not matches
//return redirect()->back()->with("error","Your current password does not matches with the password you provided. Please try again.");
return response()->json(['errors' => ['current'=> ['Current password does not match']]], 422);
}
//uncomment this if you need to validate that the new password is same as old one
if(strcmp($request->get('old_password'), $request->get('new_password')) == 0){
//Current password and new password are same
//return redirect()->back()->with("error","New Password cannot be same as your current password. Please choose a different password.");
return response()->json(['errors' => ['current'=> ['New Password cannot be same as your current password']]], 422);
}
$validatedData = $request->validate([
'old_password' => 'required',
'new_password' => 'required|string|min:6|confirmed',
]);
//Change Password
$user = Auth::user();
$user->password = Hash::make($request->get('new_password'));
$user->save();
return $user;
}
Laravel 5.8
Include this function in a controller:
public function updatePassword(Request $request)
{
$request->validate([
'password' => 'required',
'new_password' => 'required|string|confirmed|min:6|different:password'
]);
if (Hash::check($request->password, Auth::user()->password) == false)
{
return response(['message' => 'Unauthorized'], 401);
}
$user = Auth::user();
$user->password = Hash::make($request->new_password);
$user->save();
return response([
'message' => 'Your password has been updated successfully.'
]);
}
Don't forget to send new_password_confirmation as a parameter too, because when we use the validation rule confirmed for new_password for example, Laravel automatically looks for a parameter called new_password_confirmation in order to compare both fields.
You are validating request fields old_password, new_password and password_confirm here:
$this->validate($request, [
'old_password' => 'required',
'new_password' => 'required|confirmed',
'password_confirm' => 'required'
]);
however your are using request fields current and password to verify current password and set a new one:
if (!Hash::check($request->current, $user->password)) {
// ...
$user->password = Hash::make($request->password);
Validated fields and used fields should be the same.

Difficulty in changing old email to new email in Laravel

I'm having a difficulty to change the current user's email to a new email which is user input and the email's validation. EDITED
Here's my controller
public function changeuser(Request $request){
$id = Auth::user()->id;
$change_user = User::find($id);
$valid = validator($request->only('oldpass', 'newpass', 'confirmpass'), [
'olduser' => 'required|email|max:255|exists:users',
'newuser' => 'required|email|max:255|different:olduser'
], [
'newuser.required_with' => 'Choose different email.'
]);
if ($valid->fails()) {
return redirect('/manageaccount')->with('message','Failed to update email');
}
$change_user->email = $request->input('newuser');
$change_user->save();
return redirect('/manageaccount')->with('message', 'email changed successfully');
}
my blade.php which is in modal
<div class="thirdea" id="thirdea">
<label><p class="small Montserrat">Enter Old Username</p></label>
<input type="text" class="form-control small Montserrat" name="olduser" value="" id="olduser">
<label><p class="small Montserrat"> New Username</p></label>
<input type="text" class="form-control small Montserrat" name="newuser" value="" id="newuser">
</div>
my route
Route::post('/changeuser/','UserController#changeuser');
In case of update user you can try validations for email like this :
$validate = $request -> validate([
'newuser' => 'required|unique:users,email,'.$user->id
]);

validate vat number is not working properly

I have a form for a user introduce some data, the vat number and country. When the user enter some data and click in "Go to step 2" is made an ajax request to the store() method and here should be be validated the vat number based on the selected country.
But its not working, the "dd($request->country);" shows null. Do you know why?
Html:
<form method="post" id="step1" action="">
...
<div class="form-group font-size-sm">
<select class="form-control" name="country" id="country">
#foreach($countries as $country)
<option value="">{{$country}}</option>
#endforeach
</select>
</div>
<div class="form-group font-size-sm">
<label for="vat"
class="text-gray">VAT</label>
<input type="text" id="vat"
name="vat"
class="form-control" value="">
</div>
...
</form>
// store() method
public function store(Request $request, $id, $slug = null, Validator $validator){
...
$rules = [];
foreach ($request->question_required as $key => $value) {
$rule = 'string|max:255';
if ($value) {
$rule = 'required|' . $rule;
}
$rules["question.{$key}"] = $rule;
}
if ($all) {
$rules["name.*"] = 'required|max:255|string';
}
// the issue is here, country is null
dd($request->country);
dd(substr($request->country, 0, 2) . $request->vat);
//Validator::validate( substr($request->country, 0, 2).$request->vat); // false (checks format + existence)
$validator = Validator::make($request->all(), $rules, $messages);
$errors = $validator->errors();
$errors = json_decode($errors);
if ($validator->fails()) {
return response()->json([
'success' => false,
'errors' => $errors
], 422);
}
return response()->json([
'success' => true,
'message' => 'success'
], 200);
}
// jQuery that do an ajax request
Try passing value into your tag . Php is not getting any value from your input so its showing null

Categories